Java-判断两个json字符串是否相等(忽略子元素顺序)
程序员文章站
2022-04-10 14:55:50
...
使用步骤:
- 使用谷歌的Gson库,添加Maven引用:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
- 使用JsonObject的equals方法,即可判断:
private static boolean isJsonEqual(String jsonStr1, String jsonStr2)
{
JsonObject obj = (JsonObject) new JsonParser().parse(jsonStr1);
JsonObject obj1 = (JsonObject) new JsonParser().parse(jsonStr2);
return obj.equals(obj1);
}
- 示例:比较以下两个json字符串
json字符串1:
{
"value1": "11",
"value2": "22",
"value3": {
"before": 1,
"after": 2
}
}
json字符串2:
{
"value3": {
"after": 2,
"before": 1
},
"value2": "22",
"value1": "11"
}
- Junit测试:
private String jsonStr1 = " {\n" +
" \"value1\": \"11\",\n" +
" \"value2\": \"22\",\n" +
" \"value3\": {\n" +
" \"before\": 1,\n" +
" \"after\": 2\n" +
" }\n" +
" }";
private String jsonStr2 = " {\n" +
" \"value3\": {\n" +
" \"after\": 2,\n" +
" \"before\": 1\n" +
" },\n" +
" \"value2\": \"22\",\n" +
" \"value1\": \"11\"\n" +
" }\n";
private static boolean isJsonEqual(String jsonStr1, String jsonStr2)
{
JsonObject obj = (JsonObject) new JsonParser().parse(jsonStr1);
JsonObject obj1 = (JsonObject) new JsonParser().parse(jsonStr2);
return obj.equals(obj1);
}
@Test
public void isJsonEqualTest()
{
Assert.assertTrue(isJsonEqual(jsonStr1, jsonStr2));
}
注:该方法对于子数组中的元素顺序不一致的情况,还是会判断为不相等,比如:
{
"value3": [
"1",
"2"
]
}
与
{
"value3": [
"2",
"1"
]
}
判断结果为不相等