How to compare two JSon Responses when the order of response differ

Viewed 79

Below is the response I receive for my two API calls, the response is same but the order of data is out:

{"URI":"CoGroup/2","level":"total","name":null,"code":null,"baseColor":null,"secondaryColor":null,"selected":null,"value":317978,"Byyear":[],"count":10499},
{"URI":"integer/7005","level":"total","name":null,"code":null,"baseColor":null,"secondaryColor":null,"selected":null,"value":26857,"Byyear":[],"count":4542},
{"URI":"intgroup/78","level":"total","name":null,"code":null,"baseColor":null,"secondaryColor":null,"selected":null,"value":105304,"Byyear":[],"count":1653}
]

[
{"URI":"CoGroup/2","level":"total","name":null,"code":null,"baseColor":null,"secondaryColor":null,"selected":null,"value":317978,"Byyear":[],"count":10499},
{"URI":"intgroup/78","level":"total","name":null,"code":null,"baseColor":null,"secondaryColor":null,"selected":null,"value":105304,"Byyear":[],"count":1653},
{"URI":"integer/7005","level":"total","name":null,"code":null,"baseColor":null,"secondaryColor":null,"selected":null,"value":26857,"Byyear":[],"count":4542}
]

I have tried using the Jackson to compare the responses using mapper.readtree, but the results are returning as false.

ObjectMapper mapper1 = new ObjectMapper();
ObjectMapper mapper2 = new ObjectMapper();
try{
assertEquals(mapper1.readTree(respStr1), mapper2.readTree(respStr2));
}
catch(Exception e) {
System.out.println(e);
}

and 

ObjectMapper mapper1 = new ObjectMapper();
JsonNode tree1 = mapper1.readTree(respStr1);
JsonNode tree2 = mapper1.readTree(respStr2);
System.out.println(tree1.equals(tree2));

Any suggestions on how to approach for the comparison here....

1 Answers

You can use the library JSONAssert by scyscreamer for this purpose.

It would work like this:

// respStr1 and respStr2 are the two json in string
JSONAssert.assertEquals(respStr1, respStr2, JSONCompareMode.NON_EXTENSIBLE);

NON_EXTENSIBLE mode would allow assertion to pass if the json differs in order only.

Edit: JSONCompare.compareJSON(respStr1, respStr2, CompareMode.NON_EXTENSIBLE).passed() will return if the comparison passed.

Related