Best way to compare 2 JSON files in Java Best way to compare 2 JSON files in Java json json

Best way to compare 2 JSON files in Java


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


This only addresses equality, not differences.


With Jackson.

ObjectMapper mapper = new ObjectMapper();JsonNode tree1 = mapper.readTree(jsonInput1);JsonNode tree2 = mapper.readTree(jsonInput2);boolean areTheyEqual = tree1.equals(tree2);

From the JavaDoc for JsonNode.equals:

Equality for node objects is defined as full (deep) value equality. This means that it is possible to compare complete JSON trees for equality by comparing equality of root nodes.


I've done good experience with JSONAssert.

import org.junit.Test;import org.apache.commons.io.FileUtils;import org.skyscreamer.jsonassert.JSONAssert;import org.skyscreamer.jsonassert.JSONCompareMode;... @Testpublic void myTest() {  String expectedJson = FileUtils.readFileToString("/expectedFile");  String actualJson = FileUtils.readFileToString("/actualFile");  JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.STRICT);}...