Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a diff of two JSON strings using Java code

Tags:

java

json

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

like image 729
Prafull N Avatar asked Jul 09 '10 15:07

Prafull N


People also ask

Can we compare two JSON objects Java?

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.

How do you compare two JSON objects?

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.

How extract JSON data from string in Java?

JSONParser parser = new JSONParser(); JSONObject jsonObject = (JSONObject) parser. parse(yourString); String msgType = (String) jsonObject. get("MsgType");


3 Answers

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 }
}
like image 113
Martin Algesten Avatar answered Sep 20 '22 17:09

Martin Algesten


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.

like image 25
StaxMan Avatar answered Sep 20 '22 17:09

StaxMan


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).

like image 44
Justin Niessner Avatar answered Sep 17 '22 17:09

Justin Niessner