如何使用GSON获得两个json对象之间的差异? [英] How do I get differences between two json objects using GSON?

查看:138
本文介绍了如何使用GSON获得两个json对象之间的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

使用Gson在Android中使用此代码比较两个JSON对象: ABC,城市:XYZ};
String json2 ={city:XYZ,name:ABC};

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

布尔匹配= t2.equals(t1);

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

使用Gson的两个对象之间有两种方法获得差异一个JSON格式?

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

推荐答案

如果您将对象反序列化为 Map< String,Object> ,你也可以使用 Guava ,你可以使用 Maps.difference 来比较这两个结果图。

If you deserialize the objects as a Map<String, Object>, you can with Guava also, you can use Maps.difference to compare the two resulting maps.

请注意,如果您关心元素的顺序 Json 不会在 Object s的字段中保存顺序,所以此方法不会显示这些比较。

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

以下是您的操作方式:

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}

在此处了解有关 MapDifference object contains。

Read more here about what information the resulting MapDifference object contains.

这篇关于如何使用GSON获得两个json对象之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆