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.
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.
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…