Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to compare 2 JSON files in Java

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?

like image 368
James Raitsev Avatar asked Jun 29 '11 20:06

James Raitsev


People also ask

Can we compare 2 JSON files?

This means that it is possible to compare complete JSON trees for equality by comparing equality of root nodes. mapper. readTree do not works if json fields has different order. And only compares the structure of the json documents.

Can we compare two JSON objects Java?

Compare JSON Objects with Custom ComparatorThe JsonNode. equals() method works fine for most of the cases in comparing two objects. However, Jackson provides one more variant of the equals() method, i.e., JsonNode. equals(comparator, JsonNode) for configuring the custom Java Comparator object.

How do you compare two JSON objects?

Comparing Json: 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 do I compare two JSON files in beyond compare?

Step 1: Navigate in the BeyondCompare menu to: Tools-->File Formats... Step 3: Enter *. json into the file format's Mask field, and any description that will help you recall the file format's purpose.


1 Answers

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

like image 137
pacoverflow Avatar answered Sep 28 '22 15:09

pacoverflow