Getting a diff of two JSON strings using Java code

后端 未结 4 989
无人及你
无人及你 2020-12-15 21:55

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

相关标签:
4条回答
  • 2020-12-15 22:28

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

    0 讨论(0)
  • 2020-12-15 22:30

    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.

    0 讨论(0)
  • 2020-12-15 22:38

    The above answers only checks Json against equality.If you want to get a diff look at javers library. Convert the json into java objects using Jackson and then use javers compare value objects to get the diff. Here is the sample piece code.(Assuming p1,p2 are two java objects)

    Javers j = JaversBuilder.javers().build();
            Diff diff = j.compare(p1, p2);
            if (diff.hasChanges()) {
                List<Change> changes = diff.getChanges();
                for (Change change : changes) {
                    if (change instanceof ValueChange) {
                        ValueChange valChange = (ValueChange) change;
    System.out.println(valChange.getPropertyName() + " -- " + valChange.getLeft() + "--"+valchange.getRight());
    }
     }
    

    This will give you the differences as key value and the expected and actual values.

    0 讨论(0)
  • 2020-12-15 22:43

    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 }
    }
    
    0 讨论(0)
提交回复
热议问题