tags:

views:

67

answers:

2

Can anybody suggest some Java Library or Code to get a diff of two JSON Strings?

+1  A: 

Personally, I would suggest de-serializing the JSON strings back into objects and comparing the objects.

That way you don't have to worry about extra whitespace/formatting between the two JSON strings (two strings could be formatted wildly different and still represent equal objects).

Justin Niessner
Yes this is an important point, if the 2 JSON strings contain the same data but with the properties in a different order (for example), should they be considered equal?
JonoW
i am just curious if he can canonicalize the json string and then compare both the strings?
Pangea
By comparison, I mean - to identify such keys where values are differing. Basically need to identify all keys with different values .Example:String 1 : {"format":"example","content":"test", "no_diff":"no_diff"} String 2 : {"format":"example1","content":"test1", "no_diff":"no_diff"}On comparison, it should return - format and content keys with their values.
Prafull N
A: 

For one specific suggestion, you could use Jackson, bind JSON strings into JSON trees, and compare them for equality. Something like:

ObjectMapper mapper = new ObjectMapper(); JsonNode tree1 = mapper.readTree(jsonString1); JsonNode tree2 = mapper.readTree(jsonString2); if (tree1.equals(tree2)) { // yes, contents are equal -- note, ordering of arrays matters, objects not } else { // not equal }

equality comparison is by value and should work as expected with respect to JSON arrays, objects and primitive values.

StaxMan