'Compare two JSON structures in Java

I am trying to compare 2 JSON API responses in terms of structure, and ignoring the data.

Tried converting the JSON responses into Objects using Jackson implementing the following code, but it does not give me the expected results

MyObject ob = new ObjectMapper().readValue(jsonOutput, MyObject.class);

What could possibly be the best way to compare 2 JSON API responses for structure and ignoring the data.



Solution 1:[1]

Not sure if this is what you want but you have the solution of using this package. It can generate a diff out of two JSONs.

The result will be a JSON Patch (ie, RFC 6902). You can track object member deletions and removals since they will always be either add or remove operations.


EDIT from the comment (which is why it is important to fully specify the question!), it seems that what you want is a JSON Schema instead; I also happen to have an implementation which uses Jackson...

Solution 2:[2]

Given the ad-hoc nature of JSON, this simple feature isn't easy, depending on how complex the structure is. If each API just returns a single object with primitive values (null, "" string, boolean or a number), then you can collect the keys in a sorted set and compare them.

But if the JSON becomes deeply nested, this becomes more and more complex. Maybe you can write a printer for JSON which just prints the the field/key/property names sorted without the values and the JSON structure (object and array). You can then put that into a string and compare the two.

Solution 3:[3]

Parse both JSON strings into Maps and Lists. Then write a recursive-descent tree walker that compares each element, using whatever criteria you want for the comparison. The structure of the tree walker would be essentially the same as a JSON serializer, so one could start with an open-source serializer. Could probably be done in about 300-500 lines of code.

Of course, one does need to define what "matches" means. If one array has 5 elements and another 10 it's easy to say they "match" if they both are only strings or only numeric, but if they are arrays of objects then it gets messier, if you want to allow differing array counts to "match".

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 fge
Solution 2 Aaron Digulla
Solution 3 Hot Licks