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 differences between two objects using Gson in a JSON format?
有两种方法可以使用GSON格式的Gson获取两个对象之间的差异吗?
1 个解决方案
#1
9
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.
如果将对象反序列化为Map
Note that if you care about the order of the elements, Json
doesn't preserve order on the fields of Object
s, so this method won't show those comparisons.
请注意,如果您关心元素的顺序,Json不会保留对象字段的顺序,因此此方法不会显示这些比较。
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 MapDifference
object contains.
在此处阅读有关生成的MapDifference对象包含的信息的更多信息。
#1
9
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.
如果将对象反序列化为Map
Note that if you care about the order of the elements, Json
doesn't preserve order on the fields of Object
s, so this method won't show those comparisons.
请注意,如果您关心元素的顺序,Json不会保留对象字段的顺序,因此此方法不会显示这些比较。
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 MapDifference
object contains.
在此处阅读有关生成的MapDifference对象包含的信息的更多信息。