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

import com.fasterxml.jackson.databind.{ObjectMapper, JsonNode}
JsonNode beforeNode = jacksonObjectMapper.readTree(beforeJsonString);
JsonNode afterNode = jacksonObjectMapper.readTree(afterJsonString);

import com.flipkart.zjsonpatch.JsonDiff
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).

Answer from pacoverflow on Stack Overflow
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 24386833 โ€บ how-to-compare-the-json-responedata-and-sql-data-in-java
How to compare the Json responedata and sql data in java - Stack Overflow
July 16, 2021 - import java.lang.reflect.Type; import java.util.List; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class JsonCompare { public static void main(String[] args) { String jsonData = "{ \"chargeback\": 5, \"activeDisputes\": 12, \"recentUpdates\": 10, \"recentlyClosed\": 12, \"responseRequired\": 8, \"inProgress\": 4, \"closedInFavor\": 4, \"closedChargebacks\": 8 }"; Gson gson = new Gson(); DisputeSummaryarraylistobject webserviceObject = gson.fromJson(jsonData, DisputeSummaryarraylistobject.class); //DDObject DisputeSummaryarraylistobject dbObject = new DisputeSum
๐ŸŒ
Granderondecellars
granderondecellars.com โ€บ bapptn โ€บ how-to-compare-json-response-with-database-in-java
how to compare json response with database in java
The downside to this method is it will require another step in parsing the actual JSON you want return Json(new { ReturnStatus = "error", ReturnData = data }); The second method would be a little more complicated, and that would be to leverage the response object either using custom headers or status messages. One of the best courses to learn Jackson API for Java developers. Oracle Database has a huge amount of functionality that makes this easy. The JSON extension implements the JavaScript Object Notation data-interchange format. Uses the sample XML document to infer an XML schema (XSD). Quick Summary :-Building a database isn't easy at it sounds.Browse through our comparative study on databases: MongoDB vs MySQL.
Discussions

java - How to compare JSON documents and return the differences with Jackson or Gson? - Stack Overflow
I am using spring-boot to develop backend services. There is a scenario to compare 2-beans(one is the DB object and another one is the client requested object) and return the "new element","modified More on stackoverflow.com
๐ŸŒ stackoverflow.com
is it possible compare between Response (Soap /Json) and Data source using java
Hi , My scenarios is to compare between response (SOAP/Rest) and database using any of the scripting language Like Java / Groovy /Jython (Mostly Using Java )โ€ฆ More on forums.parasoft.com
๐ŸŒ forums.parasoft.com
May 18, 2017
How to compare json response with mysql query in JAVA - Stack Overflow
I am trying to comparing Json response with my sql query result. More on stackoverflow.com
๐ŸŒ stackoverflow.com
September 10, 2018
mysql - Compare JDBC Request results with JSON HTTP Request Response array data - Stack Overflow
I have a JDBC Request that contains a query like: SELECT CUSTOMER_ID, CUSTOMER_NAME, START_DATE, COMPLETE_DATE, NUMBER_OF_FINDINGS FROM CUSTOMER ORDER BY START_DATE; This returns... More on stackoverflow.com
๐ŸŒ stackoverflow.com
April 30, 2016
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ json โ€บ compare two json objects with gson
Compare Two JSON Objects with Gson | Baeldung
January 8, 2024 - Comparison of JSON in its string representation is often less effective than comparing it semantically. Here we use Gson to load the JSON and compare the data.
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ json โ€บ jackson โ€บ compare two json objects with jackson
Compare Two JSON Objects with Jackson | Baeldung
January 8, 2024 - JsonNode.equals works quite well in most cases. Jackson also provides JsonNode.equals(comparator, JsonNode) to configure a custom Java Comparator object.
๐ŸŒ
Makeseleniumeasy
makeseleniumeasy.com โ€บ 2021 โ€บ 02 โ€บ 19 โ€บ rest-assured-tutorial-68-compare-two-json-using-jackson-java-library
REST Assured Tutorial 68 โ€“ Compare Two JSON using Jackson โ€“ Java Library
February 19, 2021 - package CompareJSONUsingJackson; import org.testng.annotations.Test; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class CompareJsonArrays { String jsonArray1; String jsonArray2; ObjectMapper objectMapper; JsonNode jsonNode1; JsonNode jsonNode2; @Test public void compareTwoJsonArrays() throws JsonMappingException, JsonProcessingException { jsonArray1 = "[\r\n" + " {\r\n" + " \"lastName\": \"Mahajan\",\r\n" + " \"firs
๐ŸŒ
DZone
dzone.com โ€บ coding โ€บ languages โ€บ jsontuples: json parser and comparator in java
jsonTuples: JSON Parser and Comparator in Java
July 26, 2019 - The jsonTuples library parses JSON text to immutable JSON values, which can then be converted to List or Map for CRUD operations, and then back to JSON values. As a unique feature, jsonTuples can compare two JSON texts, or compare ANY two Java ...
Find elsewhere
Top answer
1 of 4
102

Reading the JSON documents as Maps and comparing them

You could read both JSON documents as Map<K, V>. See the below examples for Jackson and Gson:

ObjectMapper mapper = new ObjectMapper();
TypeReference<HashMap<String, Object>> type = 
    new TypeReference<HashMap<String, Object>>() {};

Map<String, Object> leftMap = mapper.readValue(leftJson, type);
Map<String, Object> rightMap = mapper.readValue(rightJson, type);
Gson gson = new Gson();
Type type = new TypeToken<Map<String, Object>>(){}.getType();

Map<String, Object> leftMap = gson.fromJson(leftJson, type);
Map<String, Object> rightMap = gson.fromJson(rightJson, type);

Then use Guava's Maps.difference(Map<K, V>, Map<K, V>) to compare them. It returns a MapDifference<K, V> instance:

MapDifference<String, Object> difference = Maps.difference(leftMap, rightMap);

If you are not happy with the result, you can consider flattening the maps and then compare them. It will provide better comparison results especially for nested objects and arrays.

Creating flat Maps for the comparison

To flat the map, you can use:

public final class FlatMapUtil {

    private FlatMapUtil() {
        throw new AssertionError("No instances for you!");
    }

    public static Map<String, Object> flatten(Map<String, Object> map) {
        return map.entrySet().stream()
                .flatMap(FlatMapUtil::flatten)
                .collect(LinkedHashMap::new, (m, e) -> m.put("/" + e.getKey(), e.getValue()), LinkedHashMap::putAll);
    }

    private static Stream<Map.Entry<String, Object>> flatten(Map.Entry<String, Object> entry) {

        if (entry == null) {
            return Stream.empty();
        }

        if (entry.getValue() instanceof Map<?, ?>) {
            return ((Map<?, ?>) entry.getValue()).entrySet().stream()
                    .flatMap(e -> flatten(new AbstractMap.SimpleEntry<>(entry.getKey() + "/" + e.getKey(), e.getValue())));
        }

        if (entry.getValue() instanceof List<?>) {
            List<?> list = (List<?>) entry.getValue();
            return IntStream.range(0, list.size())
                    .mapToObj(i -> new AbstractMap.SimpleEntry<String, Object>(entry.getKey() + "/" + i, list.get(i)))
                    .flatMap(FlatMapUtil::flatten);
        }

        return Stream.of(entry);
    }
}

It uses the JSON Pointer notation defined in the RFC 6901 for the keys, so you can easily locate the values.

Example

Consider the following JSON documents:

{
  "name": {
    "first": "John",
    "last": "Doe"
  },
  "address": null,
  "birthday": "1980-01-01",
  "company": "Acme",
  "occupation": "Software engineer",
  "phones": [
    {
      "number": "000000000",
      "type": "home"
    },
    {
      "number": "999999999",
      "type": "mobile"
    }
  ]
}
{
  "name": {
    "first": "Jane",
    "last": "Doe",
    "nickname": "Jenny"
  },
  "birthday": "1990-01-01",
  "occupation": null,
  "phones": [
    {
      "number": "111111111",
      "type": "mobile"
    }
  ],
  "favorite": true,
  "groups": [
    "close-friends",
    "gym"
  ]
}

And the following code to compare them and show the differences:

Map<String, Object> leftFlatMap = FlatMapUtil.flatten(leftMap);
Map<String, Object> rightFlatMap = FlatMapUtil.flatten(rightMap);

MapDifference<String, Object> difference = Maps.difference(leftFlatMap, rightFlatMap);

System.out.println("Entries only on the left\n--------------------------");
difference.entriesOnlyOnLeft()
          .forEach((key, value) -> System.out.println(key + ": " + value));

System.out.println("\n\nEntries only on the right\n--------------------------");
difference.entriesOnlyOnRight()
          .forEach((key, value) -> System.out.println(key + ": " + value));

System.out.println("\n\nEntries differing\n--------------------------");
difference.entriesDiffering()
          .forEach((key, value) -> System.out.println(key + ": " + value));

It will produce the following output:

Entries only on the left
--------------------------
/address: null
/phones/1/number: 999999999
/phones/1/type: mobile
/company: Acme


Entries only on the right
--------------------------
/name/nickname: Jenny
/groups/0: close-friends
/groups/1: gym
/favorite: true


Entries differing
--------------------------
/birthday: (1980-01-01, 1990-01-01)
/occupation: (Software engineer, null)
/name/first: (John, Jane)
/phones/0/number: (000000000, 111111111)
/phones/0/type: (home, mobile)
2 of 4
54

Creating a JSON Patch document

Alternatively to the approach described in the other answer, you could use the Java API for JSON Processing defined in the JSR 374 (it doesn't use on Gson or Jackson). The following dependencies are required:

<!-- Java API for JSON Processing (API) -->
<dependency>
    <groupId>javax.json</groupId>
    <artifactId>javax.json-api</artifactId>
    <version>1.1.2</version>
</dependency>

<!-- Java API for JSON Processing (implementation) -->
<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1.2</version>
</dependency>

Then you can create a JSON diff from the JSON documents. It will produce a JSON Patch document as defined in the RFC 6902:

JsonPatch diff = Json.createDiff(source, target);

When applied to the source document, the JSON Patch yields the target document. The JSON Patch can be applied to the source document using:

JsonObject patched = diff.apply(source);

Creating a JSON Merge Patch document

Depending on your needs, you could create a JSON Merge Patch document as defined in the RFC 7396:

JsonMergePatch mergeDiff = Json.createMergeDiff(source, target);

When applied to the source document, the JSON Merge Patch yields the target document. To patch the source, use:

JsonValue patched = mergeDiff.apply(source);

Pretty printing JSON documents

To pretty print the JSON documents, you can use:

System.out.println(format(diff.toJsonArray()));
System.out.println(format(mergeDiff.toJsonValue()));
public static String format(JsonValue json) {
    StringWriter stringWriter = new StringWriter();
    prettyPrint(json, stringWriter);
    return stringWriter.toString();
}

public static void prettyPrint(JsonValue json, Writer writer) {
    Map<String, Object> config =
            Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, true);
    JsonWriterFactory writerFactory = Json.createWriterFactory(config);
    try (JsonWriter jsonWriter = writerFactory.createWriter(writer)) {
        jsonWriter.write(json);
    }
}

Example

Consider the following JSON documents:

{
  "name": {
    "first": "John",
    "last": "Doe"
  },
  "address": null,
  "birthday": "1980-01-01",
  "company": "Acme",
  "occupation": "Software engineer",
  "phones": [
    {
      "number": "000000000",
      "type": "home"
    },
    {
      "number": "999999999",
      "type": "mobile"
    }
  ]
}
{
  "name": {
    "first": "Jane",
    "last": "Doe",
    "nickname": "Jenny"
  },
  "birthday": "1990-01-01",
  "occupation": null,
  "phones": [
    {
      "number": "111111111",
      "type": "mobile"
    }
  ],
  "favorite": true,
  "groups": [
    "close-friends",
    "gym"
  ]
}

And the following code to produce a JSON Patch:

JsonValue source = Json.createReader(new StringReader(leftJson)).readValue();
JsonValue target = Json.createReader(new StringReader(rightJson)).readValue();

JsonPatch diff = Json.createDiff(source.asJsonObject(), target.asJsonObject());
System.out.println(format(diff.toJsonArray()));

It will produce the following output:

[
    {
        "op": "replace",
        "path": "/name/first",
        "value": "Jane"
    },
    {
        "op": "add",
        "path": "/name/nickname",
        "value": "Jenny"
    },
    {
        "op": "remove",
        "path": "/address"
    },
    {
        "op": "replace",
        "path": "/birthday",
        "value": "1990-01-01"
    },
    {
        "op": "remove",
        "path": "/company"
    },
    {
        "op": "replace",
        "path": "/occupation",
        "value": null
    },
    {
        "op": "replace",
        "path": "/phones/1/number",
        "value": "111111111"
    },
    {
        "op": "remove",
        "path": "/phones/0"
    },
    {
        "op": "add",
        "path": "/favorite",
        "value": true
    },
    {
        "op": "add",
        "path": "/groups",
        "value": [
            "close-friends",
            "gym"
        ]
    }
]

Now consider the following code to produce a JSON Merge Patch:

JsonValue source = Json.createReader(new StringReader(leftJson)).readValue();
JsonValue target = Json.createReader(new StringReader(rightJson)).readValue();

JsonMergePatch mergeDiff = Json.createMergeDiff(source, target);
System.out.println(format(mergeDiff.toJsonValue()));

It will produce the following output:

{
    "name": {
        "first": "Jane",
        "nickname": "Jenny"
    },
    "address": null,
    "birthday": "1990-01-01",
    "company": null,
    "occupation": null,
    "phones": [
        {
            "number": "111111111",
            "type": "mobile"
        }
    ],
    "favorite": true,
    "groups": [
        "close-friends",
        "gym"
    ]
}

Different results when applying the patches

When the patch document is applied, the results are slightly different for the approaches described above. Consider the following code that applies JSON Patch to a document:

JsonPatch diff = ...
JsonValue patched = diff.apply(source.asJsonObject());
System.out.println(format(patched));

It produces:

{
    "name": {
        "first": "Jane",
        "last": "Doe",
        "nickname": "Jenny"
    },
    "birthday": "1990-01-01",
    "occupation": null,
    "phones": [
        {
            "number": "111111111",
            "type": "mobile"
        }
    ],
    "favorite": true,
    "groups": [
        "close-friends",
        "gym"
    ]
}

Now consider the following code that applies JSON Merge Patch to a document:

JsonMergePatch mergeDiff = ...
JsonValue patched = mergeDiff.apply(source);
System.out.println(format(patched));

It produces:

{
    "name": {
        "first": "Jane",
        "last": "Doe",
        "nickname": "Jenny"
    },
    "birthday": "1990-01-01",
    "phones": [
        {
            "number": "111111111",
            "type": "mobile"
        }
    ],
    "favorite": true,
    "groups": [
        "close-friends",
        "gym"
    ]
}

In the first example, the occupation property is null. In the second example, it's omitted. It's due to the null semantics on JSON Merge Patch. From the RFC 7396:

If the target does contain the member, the value is replaced. Null values in the merge patch are given special meaning to indicate the removal of existing values in the target. [...]

This design means that merge patch documents are suitable for describing modifications to JSON documents that primarily use objects for their structure and do not make use of explicit null values. The merge patch format is not appropriate for all JSON syntaxes.

๐ŸŒ
JSON Diff
jsondiff.com
JSON Diff - The semantic JSON compare tool
Validate, format, and compare two JSON documents. See the differences between the objects instead of just the new lines and mixed up properties.
๐ŸŒ
Pavantestingtools
pavantestingtools.com โ€บ 2024 โ€บ 11 โ€บ how-to-compare-json-file-with-json.html
SDET-QA Blog: How to Compare a JSON File with a JSON Response
Fetch the API Response: Use an HTTP client like REST Assured to get the JSON response. Parse JSON Data: Convert the JSON strings to comparable JSON objects. Perform Comparison: Compare the JSON objects and highlight any differences. Hereโ€™s an example of how to perform the comparison using ...
๐ŸŒ
GitHub
github.com โ€บ fslev โ€บ json-compare
GitHub - fslev/json-compare: A Java library for comparing JSONs ยท GitHub
String expected = "{\"a\":\"\\\\Qd+\\\\E\"}"; String actual = "{\"a\":\"d+\"}"; JSONCompare.assertMatches(expected, actual); // assertion passes ยท By quoting special characters, using \Q and \E, you disable the regex mechanism for that corresponding sequence. From Java Pattern docs:
Starred by 75 users
Forked by 14 users
Languages ย  Java
๐ŸŒ
Parasoft Forums
forums.parasoft.com โ€บ soatest
is it possible compare between Response (Soap /Json) and Data source using java โ€” Parasoft Forums
May 18, 2017 - Hi , My scenarios is to compare ... very well ) ... I suggest using the DB tool to send a DB query to your database and extract the data from the "results XML" using the XML data bank....
๐ŸŒ
Stanislav Myachenkov
smyachenkov.com โ€บ posts โ€บ how to compare json documents in java
How To Compare JSON Documents In Java | Stanislav Myachenkov
June 9, 2020 - Lets think about a task, where we want to know the difference between 2 or more JSON documents. We may want to do it to display the history of edits of the document to review, validate, and have a chance to roll back these changes. For example, if we have two documents describing the movie ...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 52252096 โ€บ how-to-compare-json-response-with-mysql-query-in-java
How to compare json response with mysql query in JAVA - Stack Overflow
September 10, 2018 - Comparing strings will be difficult and error prone. Better parse both your json and query result to POJOs and use equals method to compare them.
๐ŸŒ
javathinking
javathinking.com โ€บ blog โ€บ best-way-to-compare-two-json-files-in-java
Best Way to Compare Two JSON Files in Java: Intelligent Diff Presentation & Step-by-Step Guide โ€” javathinking.com
Test Edge Cases: Compare empty JSON, nested objects, arrays with duplicates, and null values. Choose the Right Library: Use JSONassert for testing, zjsonpatch for production diffs, and custom code only for unique needs. Intelligent JSON comparison in Java is critical for ensuring data integrity, debugging, and testing.
๐ŸŒ
GitHub
gist.github.com โ€บ 95c58862f54cee57ae68e58bee2378f2
Compare two JSON Objects and get Difference. ยท GitHub
Compare two JSON Objects and get Difference. GitHub Gist: instantly share code, notes, and snippets.
๐ŸŒ
QA Automation Expert
qaautomation.expert โ€บ 2024 โ€บ 09 โ€บ 03 โ€บ how-to-compare-json-file-with-json-response
How to compare JSON File with JSON Response โ€“ QA Automation Expert
September 3, 2024 - Response response = RestAssured.given().when().get("https://reqres.in/api/users/3").then().extract().response(); String expectedResponse = response.getBody().asString(); System.out.println("Response is : " + expectedResponse); // Verify the status code response.then().statusCode(200); ... Convert the JSON content from the response into another JsonNode object using the ObjectMapper.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 36873622 โ€บ compare-jdbc-request-results-with-json-http-request-response-array-data
mysql - Compare JDBC Request results with JSON HTTP Request Response array data - Stack Overflow
April 30, 2016 - String json_customerId = vars.get("customer_id"); String json_customerName = vars.get("customer_name"); String json_startedOn = vars.get("started_on"); String json_completedOn = vars.get("completed_on"); String json_numberOfFindings = vars.get("number_of_findings"); String db_customerId = vars.get("customer_id"); String db_customerName = vars.get("customer_name"); String db_startedOn = vars.get("started_on"); String db_completedOn = vars.get("completed_on"); String db_numberOfFindings = vars.get("number_of_findings"); int intN = 0 For (intN=0; intN=totalItems; intN++) if (json_customerId[intN].equals(db_customer_id[intN])) { Failure = false; print("counts match" + json_customerId + db_customer_id); } else { Failure = true; FailureMessage = "Difference detected, json_result: " + json_customerID >+ " and db_result: " + db_customer_id; } ... I'd personally do this way in Java.
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 533531 โ€บ java โ€บ compare-json-object-java-side
how to compare two json object at java side (Beginning Java forum at Coderanch)
April 6, 2011 - How can i write json object comparision? And, Please provide sample code base Thanks in advance ... I recommend using this Java library for comparing JSONs: https://github.com/fslev/json-compare It has all kinds of features.