You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将深度嵌套JSON对比结果写入含增删改的新JSON文件

融合源JSON与目标JSON变更的实现方案

你可以在现有代码基础上新增递归合并逻辑,将目标JSON的新增、删除、修改操作同步到源JSON结构中,最终生成融合后的新JSON文件。以下是修改后的完整代码:

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map.Entry;

import org.apache.commons.io.FileUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class CompareAndMergeJSON {

    public static void main(String[] args) throws IOException {
        // 读取源和目标JSON文件
        String jsonSource = FileUtils.readFileToString(new File("jsonsource.txt"), StandardCharsets.UTF_8);
        String jsonTarget = FileUtils.readFileToString(new File("jsontarget.txt"), StandardCharsets.UTF_8);

        // 解析为JsonElement
        JsonElement sourceElement = JsonParser.parseString(jsonSource);
        JsonElement targetElement = JsonParser.parseString(jsonTarget);

        // 执行合并:以源为基础,应用目标的变更
        JsonElement mergedElement = mergeJson(sourceElement, targetElement);

        // 格式化并保存合并后的JSON到文件
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String mergedJson = gson.toJson(mergedElement);
        FileUtils.writeStringToFile(new File("mergedJson.txt"), mergedJson, StandardCharsets.UTF_8);

        System.out.println("合并完成,结果已保存到mergedJson.txt");
    }

    /**
     * 递归合并两个JsonElement:以source为基础,应用target的变更
     */
    private static JsonElement mergeJson(JsonElement source, JsonElement target) {
        // 如果两者相等,直接返回源的深拷贝
        if (source.equals(target)) {
            return source.deepCopy();
        }

        // 处理数组类型
        if (source.isJsonArray() && target.isJsonArray()) {
            JsonArray sourceArr = (JsonArray) source;
            JsonArray targetArr = (JsonArray) target;
            JsonArray mergedArr = new JsonArray();

            // 合并共同索引的元素
            int minSize = Math.min(sourceArr.size(), targetArr.size());
            for (int i = 0; i < minSize; i++) {
                mergedArr.add(mergeJson(sourceArr.get(i), targetArr.get(i)));
            }

            // 目标数组更长,新增元素
            if (targetArr.size() > minSize) {
                for (int i = minSize; i < targetArr.size(); i++) {
                    mergedArr.add(targetArr.get(i).deepCopy());
                }
            }

            return mergedArr;
        }

        // 处理对象类型
        else if (source.isJsonObject() && target.isJsonObject()) {
            JsonObject sourceObj = (JsonObject) source;
            JsonObject targetObj = (JsonObject) target;
            JsonObject mergedObj = new JsonObject();

            // 先处理目标中的所有键:存在则合并,不存在则新增
            for (Entry<String, JsonElement> targetEntry : targetObj.entrySet()) {
                String key = targetEntry.getKey();
                JsonElement targetValue = targetEntry.getValue();
                if (sourceObj.has(key)) {
                    mergedObj.add(key, mergeJson(sourceObj.get(key), targetValue));
                } else {
                    mergedObj.add(key, targetValue.deepCopy());
                }
            }

            return mergedObj;
        }

        // 处理基本类型或类型不一致的情况:直接用目标值替换源值
        else {
            return target.deepCopy();
        }
    }

    // 保留原有的compareJson方法,用于输出差异(可选)
    private static void compareJson(JsonElement json, JsonElement other, String path) {
        if (json.equals(other)) {
            return;
        }

        if (json.isJsonArray() && other.isJsonArray()) {
            JsonArray arrJ = (JsonArray) json;
            JsonArray arrO = (JsonArray) other;

            int size = Math.min(arrJ.size(), arrO.size());
            for (int i = 0; i < size; i++) {
                compareJson(arrJ.get(i), arrO.get(i), path + "/" + i);
            }
            if (arrJ.size() > arrO.size()) {
                for (int i = arrO.size(); i < arrJ.size(); i++) {
                    System.out.println(path + "/ deleted array value: " + arrJ.get(i));
                }
            } else if (arrJ.size() < arrO.size()) {
                for (int i = arrJ.size(); i < arrO.size(); i++) {
                    System.out.println(path + "/ added array value: " + arrO.get(i));
                }
            }
        } else if (json.isJsonObject() && other.isJsonObject()) {
            JsonObject objJ = (JsonObject) json;
            JsonObject objO = (JsonObject) other;

            for (Entry<String, JsonElement> entry : objJ.entrySet()) {
                String key = entry.getKey();
                JsonElement value = entry.getValue();
                if (objO.has(key)) {
                    compareJson(value, objO.get(key), path + "/" + key);
                } else {
                    System.out.println(path + "/ deleted object entry: \"" + key + "\": " + value);
                }
            }
            for (Entry<String, JsonElement> entry : objO.entrySet()) {
                String key = entry.getKey();
                JsonElement value = entry.getValue();
                if (!objJ.has(key)) {
                    System.out.println(path + "/ added object entry: \"" + key + "\": " + value);
                }
            }
        } else if (json.isJsonPrimitive() && other.isJsonPrimitive()) {
            System.out.println(path + "/ value changed: " + json + " -> " + other);
        } else {
            System.out.println(path + "/ element changed: " + json + " -> " + other);
        }
    }
}

关键逻辑说明

  1. 递归合并方法mergeJson:

    • 数组处理:合并共同索引的元素,目标数组更长则新增元素,更短则自动截断源数组(实现删除操作)
    • 对象处理:仅保留目标中存在的键,存在的键递归合并值,不存在的键直接新增;自动排除源中存在但目标没有的键(实现删除操作)
    • 基本类型/类型不一致:直接用目标值替换源值,覆盖原有内容
  2. 结果保存:使用GsonBuilder格式化输出JSON,确保可读性,再通过FileUtils写入文件

  3. 依赖说明:确保项目中引入了commons-io和gson依赖,版本兼容即可

内容的提问来源于stack exchange,提问作者Ebony Maw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 09:05:22