Compare JSON with nested arrays and jsons (the order of the arrays doesn't matter)

Hello I am trying to compare two json in java, each key can contain a json object or an array of json objects, and each one can also be an array or json.

Here's an example Json:

{
  "id": "123123asd123",
  "attributes": [
      {
         "name": "apps",
         "values": [
             "111",
             "222"
             ]
      },
      {
         "name": "city",
         "values": [
              "NY"
              ]
      }
    ]
}

      

I want to get two json from this kind and compare them without worrying about the order of the arrays. As you can see the key attributes are a json array, so if I have another json like this and an element in the key city array in front of the apps, I want the test to pass. as well as numbers inside app values ​​which I don't need if it's 111.222 or 222.111

If anyone knows of any external java library that does this badly, hear. Or any idea how to implement this, compare manually? or even an idea to have this kind of json and refactor it so it will be easy to compare the share that is with me.

+3


source to share


1 answer


Take a look at this library, it is cool, I use it all day for my Webservice test:

https://github.com/jayway/JsonPath



@Test
public void test() {
    String json = "{\n" +
            "  \"id\": \"123123asd123\",\n" +
            "  \"attributes\": [\n" +
            "      {\n" +
            "         \"name\": \"apps\",\n" +
            "         \"values\": [\n" +
            "             \"111\",\n" +
            "             \"222\"\n" +
            "             ]\n" +
            "      },\n" +
            "      {\n" +
            "         \"name\": \"city\",\n" +
            "         \"values\": [\n" +
            "              \"NY\"\n" +
            "              ]\n" +
            "      }\n" +
            "    ]\n" +
            "}";

    List<String> names = JsonPath.read(json, "$.attributes[*].name");
    for(String name : names) {
        //TODO assert that name is in other list from other json
    }

      

+1


source







All Articles