Can anybody suggest some Java Library or Code to get a diff of two JSON Strings?
Compare Two JSON Objects With a Custom Comparatorequals works quite well in most cases. Jackson also provides JsonNode. equals(comparator, JsonNode) to configure a custom Java Comparator object.
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.
JSONParser parser = new JSONParser(); JSONObject jsonObject = (JSONObject) parser. parse(yourString); String msgType = (String) jsonObject. get("MsgType");
I had the exact same problem and ended up writing my own library:
https://github.com/algesten/jsondiff
It does both diffing/patching.
Diffs are JSON-objects themselves and have a simple syntax for object merge/replace and array insert/replace.
Example:
original
{
a: { b: 42 }
}
patch
{
"~a" { c: 43 }
}
The ~
indicates an object merge.
result
{
a: { b: 42, c: 43 }
}
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.
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).
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