java
在这里插入代码片
package cn.test;
import com.google.gson.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Set;
public class JsonDiff {
public static void main(String[] args) throws IOException {
String json1 = new String(Files.readAllBytes(Paths.get("/IdeaProjects/hello/src/main/java/cn/test/json1.txt")), StandardCharsets.UTF_8);
String json2 = new String(Files.readAllBytes(Paths.get("/IdeaProjects/hello/src/main/java/cn/test/json2.txt")), StandardCharsets.UTF_8);
diffJsonObjects(json1, json2);
}
public static void diffJsonObjects(String json1, String json2) {
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonElement element1 = parser.parse(json1);
JsonElement element2 = parser.parse(json2);
diffElements("root", element1, element2);
}
private static void diffElements(String path, JsonElement elem1, JsonElement elem2) {
if (!elem1.equals(elem2)) {
if (elem1.isJsonObject() && elem2.isJsonObject()) {
diffJsonObjects(path, elem1.getAsJsonObject(), elem2.getAsJsonObject());
} else if (elem1.isJsonArray() && elem2.isJsonArray()) {
diffJsonArrays(path, elem1.getAsJsonArray(), elem2.getAsJsonArray());
} else {
System.out.println("Difference at path '" + path + "': " + elem1 + " != " + elem2);
}
}
}
private static void diffJsonObjects(String path, JsonObject obj1, JsonObject obj2) {
Set<Map.Entry<String, JsonElement>> entries1 = obj1.entrySet();
Set<Map.Entry<String, JsonElement>> entries2 = obj2.entrySet();
for (Map.Entry<String, JsonElement> entry : entries1) {
String key = entry.getKey();
if (!obj2.has(key)) {
System.out.println("Missing in second JSON at path '" + path + "." + key + "': " + entry.getValue());
} else {
diffElements(path + "." + key, entry.getValue(), obj2.get(key));
}
}
for (Map.Entry<String, JsonElement> entry : entries2) {
if (!obj1.has(entry.getKey())) {
System.out.println("Missing in first JSON at path '" + path + "." + entry.getKey() + "': " + entry.getValue());
}
}
}
private static void diffJsonArrays(String path, JsonArray arr1, JsonArray arr2) {
// 注意:这里简化处理,仅比较数组长度和按索引比较元素,实际应用中可能需要更复杂的逻辑处理不同长度或元素顺序变化的情况。
if (arr1.size() != arr2.size()) {
System.out.println("Array size difference at path '" + path + "': " + arr1.size() + " != " + arr2.size());
} else {
for (int i = 0; i < arr1.size(); i++) {
diffElements(path + "[" + i + "]", arr1.get(i), arr2.get(i));
}
}
}
}