How to get the differences between two json objects using GSON?

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

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 to get the differences between two objects using Gson in JSON format?

+4
java json android gson
source share
1 answer

If you deserialize objects like Map<String, Object> , you can Guava , you can use Maps.difference to compare two resulting maps.

Note that if you care about the order of the elements, Json does not maintain order in the Object s fields, so this method will not show these comparisons.

Here's how 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 displays:

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

Learn more about what information is contained in the MapDifference object.

+7
source share

All Articles