Best way to compare two JSON files in Java

Viewed 123197

How would you suggest this task is approached?

The challenge as i see it is in presenting diff information intelligently. Before i go reinventing the wheel, is there an accepted approach of how such a comparison should be handled?

10 Answers

The easiest way to compare json strings is using JSONCompare from JSONAssert library. The advantage is, it's not limited to structure only and can compare values if you wish:

JSONCompareResult result = 
     JSONCompare.compareJSON(json1, json2, JSONCompareMode.STRICT);
System.out.println(result.toString());

which will output something like:

Expected: VALUE1
     got: VALUE2
 ; field1.field2

In case if want to compare two JSON Ignoring the order of elements/object, see if this library helps you.

Usage:

List<Diff> diff = new DnjsonDiff().getDiff(String left, String right)
Left =[{"name":"Bob","businessKey":"4444"},{"name":"John","businessKey":"5555"}]
Right = [{"name":"Bob","businessKey":"6666"},{"name":"John", "businessKey":"4444"}]

Diff:

[
    {
        "op": "replace",
        "configuredValue": "John",
        "intendedValue": "Bob",
        "businessKey": "4444"
    },
    {
        "op": "remove",
        "configuredValue": null,
        "intendedValue": "{\"name\":\"John\",\"businessKey\":\"5555\"}",
        "businessKey": "5555"
    },
    {
        "op": "add",
        "configuredValue": "{\"name\":\"Bob\",\"businessKey\":\"6666\"}",
        "intendedValue": null,
        "businessKey": "null"
    }
]

You can use below dependancy to compare Json with STRICT,LENIENT,IGNORE_ORDER etc.

<dependency>
    <groupId>org.skyscreamer</groupId>
    <artifactId>jsonassert</artifactId>
    <version>1.5.0</version>
    <scope>test</scope>
</dependency>

  public static boolean isTwoJsonEquals(JSONObject firstObj,JSONObject secondObj, JSONCompareMode compareMode){
    try {
      JSONCompareResult result = JSONCompare.compareJSON(firstObj, secondObj, compareMode);

      return result.passed();
    } catch (JSONException e) {
      e.printStackTrace();
    }
    return false;
  }
Related