Best way to compare 2 JSON files in Java

后端 未结 10 663
囚心锁ツ
囚心锁ツ 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: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).

提交回复
热议问题