java 如何使用 GSON 比较两个 JSON 字符串的相等性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25655404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:24:35  来源:igfitidea点击:

How to compare two JSON Strings for equality using GSON?

javajsongsonequality

提问by john

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

我正在尝试比较两个 JSON 字符串的相等性。我找到了这个使用 Hymanson 的解决方案,如下所示,但在我的所有项目中我都使用 GSON,所以我需要使用 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?

有没有办法使用 GSON 比较两个 JSON 字符串的相等性?

回答by Akshay

According to this answeryou 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),因此如果这不起作用,那么其中之一可能会有所帮助。

回答by Pawel Veselov

I don't believe that Gson library makes any statements that the JSON output from two equal JSON elements will be the same, mostly due to the order of properties in objects, since the standard doesn't require any kind of order. Gson library itself doesn't offer a functionality to compare JSON elements or serialized representation thereof. One can write a function that will compare two JSON elements and properly descend into the underlying compound structures (i.e. arrays and objects).

我不相信 Gson 库做出任何声明,即来自两个相等 JSON 元素的 JSON 输出将是相同的,这主要是由于对象中属性的顺序,因为标准不需要任何类型的顺序。Gson 库本身不提供比较 JSON 元素或其序列化表示的功能。可以编写一个函数来比较两个 JSON 元素并正确地下降到底层复合结构(即数组和对象)。

I was able to find this article herethat seems to contain a working comparison function.

我能够在这里找到这篇文章,它似乎包含一个有效的比较函数。