如何使用GSON比较两个JSON字符串是否相等? [英] How to compare two JSON Strings for equality using GSON?

查看:528
本文介绍了如何使用GSON比较两个JSON字符串是否相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图比较两个JSON字符串是否相等。我发现这个使用Jackson的解决方案,如下所示,但在我使用GSON的所有项目中,我需要做同样的事情使用GSON的东西。

  ObjectMapper mapper = new ObjectMapper(); 
JsonNode tree1 = mapper.readTree(jsonString1);
JsonNode tree2 = mapper.readTree(jsonString2);
if(tree1.equals(tree2)){
// yes,内容相同 - 注意,数组排序很重要,对象不是
} else {
// not等于
}

有没有什么办法可以比较两个JSON字符串是否相等? / p>

解决方案

根据这个答案你可以使用这个:

  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);

不幸的是,我猜这并不像您希望的那么干净,但它应该起作用。

在任何情况下,查看该线程中的其他答案(尽管不是所有的都使用GSON)可能会有所帮助,所以如果这不起作用,或许其中一个可能。


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?

解决方案

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.

这篇关于如何使用GSON比较两个JSON字符串是否相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆