Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I used this code to compare two JSON object 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 two get the differences between two objects using Gson in a JSON format?

like image 969
Ali Avatar asked Sep 01 '15 03:09

Ali


1 Answers

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

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

like image 137
durron597 Avatar answered Oct 26 '22 23:10

durron597