Best way to compare 2 JSON files in Java

后端 未结 10 645
囚心锁ツ
囚心锁ツ 2020-12-13 13:56

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

相关标签:
10条回答
  • 2020-12-13 14:01

    You could try the XStream's architecture, handling of JSON mappings

    Also, take a look at this post: Comparing two XML files & generating a third with XMLDiff in C#. It's in C# but the logic is the same.

    0 讨论(0)
  • 2020-12-13 14:02

    I recommend the zjsonpatch library, which presents the diff information in accordance with RFC 6902 (JSON Patch). You can use it with Jackson:

    JsonNode beforeNode = jacksonObjectMapper.readTree(beforeJsonString);
    JsonNode afterNode = jacksonObjectMapper.readTree(afterJsonString);
    JsonNode patch = JsonDiff.asJson(beforeNode, afterNode);
    String diffs = patch.toString();
    

    This library is better than fge-json-patch (which was mentioned in another answer) because it can detect items being inserted/removed from arrays. Fge-json-patch cannot handle that (if an item is inserted into the middle of an array, it will think that item and every item after that was changed since they are all shifted over by one).

    0 讨论(0)
  • 2020-12-13 14:07

    I had a similar 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)
  • 2020-12-13 14:07

    json-lib

    What I would do is parse the json data using json-lib. This will result in regular java objects which you can compare using the equals methods. This is only valid though assuming the guys from json-lib properly implemented the equals method, but that you can easily test.

    0 讨论(0)
  • 2020-12-13 14:07

    For people who are already using Jackson, I recommend json-patch

    final JsonNode patchNode = JsonDiff.asJson(firstNode, secondNode);
    System.out.println("Diff=" + m.writeValueAsString(patchNode));
    
    0 讨论(0)
  • 2020-12-13 14:14

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