Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
435 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...