如何使用 GSON 获取两个 json 对象之间的差异?

How do I get differences between two json objects using GSON?

我使用这段代码在 Android 中使用 Gson 比较两个 JSON 对象:

String json1 = "{\"name\": \"ABC\", \"city\": \"XYZ\"}";
String json2 = "{\"city\": \"XYZ\", \"name\": \"ABC\"}";

JsonParser parser = new JsonParser();
JsonElement t1 = parser.parse(json1);
JsonElement t2 = parser.parse(json2);

boolean match = t2.equals(t1);

有什么方法可以让两个人使用 JSON 格式的 Gson 获得两个对象之间的 差异

如果将对象反序列化为 Map<String, Object>,则可以使用 Guava also, you can use Maps.difference 比较两个生成的映射。

请注意,如果您关心元素的 顺序 Json 不会保留 Object 字段的顺序,因此这方法不会显示这些比较。

这是你的做法:

public static void main(String[] args) {
  String json1 = "{\"name\":\"ABC\", \"city\":\"XYZ\", \"state\":\"CA\"}";
  String json2 = "{\"city\":\"XYZ\", \"street\":\"123 anyplace\", \"name\":\"ABC\"}";

  Gson g = new Gson();
  Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
  Map<String, Object> firstMap = g.fromJson(json1, mapType);
  Map<String, Object> secondMap = g.fromJson(json2, mapType);
  System.out.println(Maps.difference(firstMap, secondMap));
}

这个程序输出:

not equal: only on left={state=CA}: only on right={street=123 anyplace}

在此处详细了解结果 MapDifference 对象包含的信息。