我正在尝试比较两个 JSON 字符串是否相等。我找到了这个 solution它使用 Jackson 如下所示,但在我所有的项目中我都使用 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
}
有什么方法可以使用 GSON 比较两个 JSON 字符串是否相等?
最佳答案
根据 this answer你可以使用这个:
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),因此如果这不起作用,也许其中之一可能。
关于java - 如何使用 GSON 比较两个 JSON 字符串是否相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25655404/