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

ruarlubt  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(238)

我使用这段代码在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来获得两个对象之间的 * 差异 *?

zbq4xfa0

zbq4xfa01#

如果您将对象还原序列化为Map<String, Object>,您也可以使用Guava,您可以使用Maps.difference来比较两个产生的Map。
请注意,如果您关心元素的 orderJson并不保持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对象包含哪些信息的信息。

相关问题