Java-判断两个json字符串是否相等(忽略子元素顺序)

使用步骤:

  1. 使用谷歌的Gson库,添加Maven引用:
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>
  1. 使用JsonObjectequals方法,即可判断:
    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);
    }
  1. 示例:比较以下两个json字符串

json字符串1:

  {
    "value1": "11",
    "value2": "22",
    "value3": {
      "before": 1,
      "after": 2
    }
  }

json字符串2:

  {
    "value3": {
      "after": 2,
      "before": 1
    },
    "value2": "22",
    "value1": "11"
  }

  1. 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"
    ]
  }

判断结果为不相等

    原文作者:浊酒入清梦
    原文地址: https://blog.csdn.net/m0_37862405/article/details/97668538
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞