Try Skyscreamer's JSONAssert.

Its non-strict mode has two major advantages that make it less brittle:

  • Object extensibility (e.g. With an expected value of {id:1}, this would still pass: {id:1,moredata:'x'}.)
  • Loose array ordering (e.g. ['dog','cat']==['cat','dog'])

In strict mode it behaves more like json-lib's test class.

A test looks something like this:

@Test
public void testGetFriends() {
    JSONObject data = getRESTData("/friends/367.json");
    String expected = "{friends:[{id:123,name:\"Corby Page\"}"
        + ",{id:456,name:\"Solomon Duskis\"}]}";
    JSONAssert.assertEquals(expected, data, false);
}

The parameters in the JSONAssert.assertEquals() call are expectedJSONString, actualDataString, and isStrict.

The result messages are pretty clear, which is important when comparing really big JSON objects.

Answer from Carter Page on Stack Overflow
Top answer
1 of 16
204

Try Skyscreamer's JSONAssert.

Its non-strict mode has two major advantages that make it less brittle:

  • Object extensibility (e.g. With an expected value of {id:1}, this would still pass: {id:1,moredata:'x'}.)
  • Loose array ordering (e.g. ['dog','cat']==['cat','dog'])

In strict mode it behaves more like json-lib's test class.

A test looks something like this:

@Test
public void testGetFriends() {
    JSONObject data = getRESTData("/friends/367.json");
    String expected = "{friends:[{id:123,name:\"Corby Page\"}"
        + ",{id:456,name:\"Solomon Duskis\"}]}";
    JSONAssert.assertEquals(expected, data, false);
}

The parameters in the JSONAssert.assertEquals() call are expectedJSONString, actualDataString, and isStrict.

The result messages are pretty clear, which is important when comparing really big JSON objects.

2 of 16
107

As a general architectural point, I usually advise against letting dependencies on a particular serialization format bleed out beyond your storage/networking layer; thus, I'd first recommend that you consider testing equality between your own application objects rather than their JSON manifestations.

Having said that, I'm currently a big fan of Jackson which my quick read of their ObjectNode.equals() implementation suggests does the set membership comparison that you want:

public boolean equals(Object o)
{
    if (o == this) return true;
    if (o == null) return false;
    if (o.getClass() != getClass()) {
        return false;
    }
    ObjectNode other = (ObjectNode) o;
    if (other.size() != size()) {
        return false;
    }
    if (_children != null) {
        for (Map.Entry<String, JsonNode> en : _children.entrySet()) {
            String key = en.getKey();
            JsonNode value = en.getValue();

            JsonNode otherValue = other.get(key);

            if (otherValue == null || !otherValue.equals(value)) {
                return false;
            }
        }
    }
    return true;
}
🌐
GitHub
github.com › lukas-krecan › JsonUnit
GitHub - lukas-krecan/JsonUnit: Compare JSON in your Unit Tests · GitHub
JsonUnit parses expected values leniently, so you do not have to quote keys, and you can use single quotes instead of double quotes. Please note that the actual value being compared is parsed in strict mode. assertThatJson("{\"a\":\"1\", \"b\":2}").isEqualTo("{b:2, a:'1'}"); If you need to customize Jackson 2 Object Mapper, you can do using SPI. Implement net.javacrumbs.jsonunit.providers.Jackson2ObjectMapperProvider.
Starred by 984 users
Forked by 119 users
Languages   Java 94.9% | Kotlin 5.1%
🌐
Baeldung
baeldung.com › home › testing › introduction to jsonassert
Introduction to JSONassert | Baeldung
January 8, 2024 - String actual = "{id:123, name:\"John\", zip:\"33025\"}"; JSONAssert.assertEquals( "{id:123,name:\"John\"}", actual, JSONCompareMode.LENIENT); As we can see, the real variable contains an additional field zip which is not present in the expected String. Still, the test will pass. This concept is useful in the application development. This means that our APIs can grow, returning additional fields as required, without breaking the existing tests. The behavior mentioned in the previous sub-section can be easily changed by using the STRICT comparison mode:
🌐
Skyscreamer
jsonassert.skyscreamer.org
JSONAssert - Write JSON Unit Tests with Less Code - Introduction
Under the covers, JSONassert converts your string into a JSON object and compares the logical structure and data with the actual JSON. When strict is set to false (recommended), it forgives reordering data and extending results (as long as all the expected elements are there), making tests less brittle. Supported test frameworks: JUnit ·
🌐
Medium
medium.com › threadsafe › how-to-compare-two-json-structures-in-java-when-the-order-of-fields-keeps-changing-f844df37e45a
How to compare two JSON objects in Java tests and when the order of values is not important | ThreadSafe
June 17, 2025 - When I am writing tests to confirm the JSON structure generated in the API with the expected structure, I almost always prefer to use the JSON path for this job, but In some scenarios, you can’t use the JSON path and write one assertion for each field in the expected JSON result, for example when your API produces a very large JSON response. In these cases, maybe it is a good idea to have the expected JSON output in a file and then compare the produced JSON result with that to confirm that the result is identical to the content of the expected JSON file.
🌐
Java Code Geeks
javacodegeeks.com › home › core java
JUnit Hamcrest Matcher for JSON - Java Code Geeks
March 12, 2018 - In order to make it simpler to write such unit tests, I have written a Hamcrest Matcher called IsEqualJSON for comparing JSON objects. It still uses JSONassert but allows you to express your tests in a more fluent way. ... import static org.junit.Assert.*; import static testutil.IsEqualJSON.*; assertThat(Arrays.asList("apple", "banana"), equalToJSON("[\"apple\", \"banana\"]")); // you can also have your expected JSON read from a file assertThat(Arrays.asList("apple", "banana"), equalToJSONInFile("fruits.json"));
🌐
GitHub
github.com › fslev › json-compare
GitHub - fslev/json-compare: A Java library for comparing JSONs · GitHub
Compare any JSON convertible Java objects and check the differences between them when matching fails. The library has some tweaks which helps you make assertions without writing any code at all.
Starred by 75 users
Forked by 14 users
Languages   Java
🌐
Baeldung
baeldung.com › home › json › jackson › compare two json objects with jackson
Compare Two JSON Objects with Jackson | Baeldung
January 8, 2024 - Learn how to use Jackson to compare two JSON objects using the built-in comparator and a custom comparator
Find elsewhere
🌐
JSON Compare
fslev.github.io › json-compare
JSON Compare | Java library for comparing Jsons
Compare any JSON convertible Java objects and check the differences between them when matching fails. The library has some tweaks which helps you make assertions without writing any code at all. Compare modes · Regex support · Differences · Tweaks · Json Path support · Extended · Junit ...
🌐
CodingTechRoom
codingtechroom.com › question › -compare-json-responses-junit-jsonassert
How to Compare JSON Responses Using JUnit and JSONAssert? - CodingTechRoom
import static org.junit.jupite... false); } } Comparing JSON responses in Java can be efficiently managed using the JUnit testing framework in conjunction with the JSONAssert library....
🌐
How to do in Java
howtodoinjava.com › home › java libraries › guide to jsonassert (with examples)
Guide to JSONassert (with Examples)
September 3, 2022 - The extended fields mean that the actual response contains more fields than the comparison string. JSONassert has inbuilt support for the following modes while comparing the JSON:
🌐
GitHub
github.com › skyscreamer › JSONassert › blob › master › src › main › java › org › skyscreamer › jsonassert › JSONCompare.java
JSONassert/src/main/java/org/skyscreamer/jsonassert/JSONCompare.java at master · skyscreamer/JSONassert
* Provides API to compare two JSON entities. This is the backend to {@link JSONAssert}, but it can · * be programmed against directly to access the functionality. (eg, to make something that works with a · * non-JUnit test framework)  ...
Author   skyscreamer
🌐
javaspring
javaspring.net › blog › ignore-specific-node-within-array-when-comparing-two-json-in-java
How to Compare Two JSON Strings in Java 8 and Ignore Specific Nodes Within Arrays Using JSONAssert — javaspring.net
December 10, 2019 - Let’s test the comparator with the earlier user array example: import org.junit.Test; import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONCompareMode; import java.util.Arrays; public class IgnoreArrayNodesTest { @Test public void testIgnoreArrayNodes() throws Exception { // Expected JSON with hardcoded IDs String expectedJson = "{" + "\"users\": [" + "{\"id\": 1, \"name\": \"Alice\"}," + "{\"id\": 2, \"name\": \"Bob\"}" + "]" + "}"; // Actual JSON with different IDs (to be ignored) String actualJson = "{" + "\"users\": [" + "{\"id\": 999, \"name\": \"Alice\"},
🌐
Blogger
madhukaudantha.blogspot.com › 2014 › 03 › comparing-json-java-testing.html
Madhuka: Comparing JSON java testing
March 3, 2014 - When writting unit test It is worth to know how to comapre JSON correctly and with effective manner. You can try skyscreamer, Where I used t...
🌐
GitHub
github.com › eBay › json-comparison › blob › master › src › test › java › com › json › comparison › JsonCompareTest.java
json-comparison/src/test/java/com/json/comparison/JsonCompareTest.java at master · eBay/json-comparison
package com.json.comparison; · import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; · import java.io.IOException; import java.net.URL; import java.util.List; import java.util.stream.Collectors; ·
Author   eBay