I'm looking for a JSON paring library that supports comparing two JSON objects' structures, ignoring values, child order, and - if possible - optionally ignoring additional elements in the response; specifically for unit testing JSON returning from a web service against an expected structure. (I'd like to pass into the assert method a sample response and compare its structure to the actual response - instead of having to write asserts for each node. Getting different values back isn't a problem, as long as the structure is fine.)
Do any of the major JSON libraries support this? (This question is basically the same as Compare two JSON objects in Java, but I want the assert to ignore the values in my JSON structure, which might look like the example found on Wikipedia...)
Comparing json is quite simple, we can use '==' operator, Note: '==' and 'is' operator are not same, '==' operator is use to check equality of values , whereas 'is' operator is used to check reference equality, hence one should use '==' operator, 'is' operator will not give expected result.
Compare JSON Objects with Custom Comparator The JsonNode. equals() method works fine for most of the cases in comparing two objects. However, Jackson provides one more variant of the equals() method, i.e., JsonNode. equals(comparator, JsonNode) for configuring the custom Java Comparator object.
Use json. dumps() and the equal-to operator to compare JSON objects regardless of order. Call json. dumps(json_object, sort_keys) with sort_keys set to True on each json_object to return the object with its key-value pairs sorted in ascending order by the keys.
Your first code step would be to convert the JSON string to an object, using JSON. parse . Then you can use Object. keys to get all keys from the first object, and you can loop over these keys to see the difference in values in the two objects.
You may want to have a look at Guava and its Equivalence
.
If for instance you use Jackson, you would write an Equivalence<JsonNode>
, which you would customize for your needs.
Here is an example of such an Equivalence
, which considers two JSON values equal if all numbers, recursively, are mathematically equal.
Usage: yourEquivalence.equivalent(node1, node2)
.
Another solution would be to write a POJO which serializes to the JSON you want and attempt to deserialize your JSON to said POJO. If deserialization fails your structure is wrong.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With