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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32323256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:20:59  来源:igfitidea点击:

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

javaandroidjsongson

提问by Ali

I used this code to compare two JSON object using Gson in Android:

我使用此代码在 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);

Is there any way two get the differencesbetween two objects using Gson in a JSON format?

有没有办法让两个使用 JSON 格式的 Gson 的对象之间的差异

采纳答案by durron597

If you deserialize the objects as a Map<String, Object>, you can with Guavaalso, you can use Maps.differenceto compare the two resulting maps.

如果反序列化对象的Map<String, Object>,你可以用番石榴还,您可以使用Maps.difference两个产生的地图相比。

Note that if you care about the orderof the elements, Jsondoesn't preserve order on the fields of Objects, so this method won't show those comparisons.

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

Here's the way you do it:

这是你的方法:

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));
}

This program outputs:

该程序输出:

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

Read more here about what information the resulting MapDifferenceobject contains.

在此处阅读有关结果MapDifference对象包含哪些信息的更多信息。