Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...