How to compare two JSON Strings for equality using GSON?

为君一笑 提交于 2019-12-30 09:55:34

问题


I am trying to compare two JSON Strings for equality. I found this solution which uses Jackson as shown below but in all my project I am using GSON so I need to do the same thing using GSON.

ObjectMapper mapper = new ObjectMapper();
JsonNode tree1 = mapper.readTree(jsonString1);
JsonNode tree2 = mapper.readTree(jsonString2);
if (tree1.equals(tree2)) { 
  // yes, contents are equal -- note, ordering of arrays matters, objects not
} else { 
  // not equal
}

Is there any way to compare two JSON String for equality using GSON?


回答1:


According to this answer you could use this:

JsonParser parser = new JsonParser();
JsonElement o1 = parser.parse("{a : {a : 2}, b : 2}");
JsonElement o2 = parser.parse("{b : 2, a : {a : 2}}");
assertEquals(o1, o2);

Unfortunately I'm guessing this isn't quite as clean as you were hoping, but it should work.

In any case it might be helpful to look through the other answers in that thread (although not all use GSON), so if this doesn't work out, perhaps one of those might.



来源:https://stackoverflow.com/questions/25655404/how-to-compare-two-json-strings-for-equality-using-gson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!