Compare JSON Arrays Using JSONAssert Library

In modern software development, working with JSON data has become a daily routine. JSON structures, whether simple or complex, are often used for data exchange between systems. Comparing JSON arrays is a critical aspect of testing APIs, validating responses, or handling dynamic data scenarios. This is where the JSONAssert library becomes invaluable.

JSONAssert is a powerful library for comparing JSON structures in Java, allowing for flexible and precise validation without manually parsing JSON. In this blog post, we'll focus on comparing JSON arrays using JSONAssert.


What Is JSONAssert?

JSONAssert is a lightweight library provided by the JSON.org ecosystem that helps compare JSON strings without needing to convert them into Java objects. It is particularly useful when verifying REST API responses in automated tests.

Key Features of JSONAssert:

  • Lenient or Strict Comparison: Offers control over how precise the comparison needs to be.
  • Works Directly on JSON Strings: Eliminates the need for deserialization.
  • Easy Integration: Works seamlessly with JUnit or TestNG.

Maven Dependency

To use JSONAssert in your project, include the following Maven dependency:

<dependency>

    <groupId>org.skyscreamer</groupId>

    <artifactId>jsonassert</artifactId>

    <version>1.5.1</version> <!-- Use the latest version -->

    <scope>test</scope>

</dependency>

JSON Array Comparison Scenarios

1. Strict Comparison

Strict comparison ensures the arrays are identical, including the order of elements.

Example:

import org.skyscreamer.jsonassert.JSONAssert;

public class JSONAssertStrictExample {
    public static void main(String[] args) {
        String expected = "[{\"id\":1, \"name\":\"John\"}, {\"id\":2, \"name\":\"Jane\"}]";
        String actual = "[{\"id\":1, \"name\":\"John\"}, {\"id\":2, \"name\":\"Jane\"}]";

        try {
            JSONAssert.assertEquals(expected, actual, true); // Strict comparison
            System.out.println("Arrays match exactly.");
        } catch (AssertionError e) {
            System.out.println("Arrays do not match: " + e.getMessage());
        }
    }
}

Output:

Arrays match exactly.

If the order or content differs, the assertion will fail.


2. Lenient Comparison

Lenient comparison allows arrays to match regardless of the order of elements.

Example: 

import org.skyscreamer.jsonassert.JSONAssert;

public class JSONAssertLenientExample {
    public static void main(String[] args) {
        String expected = "[{\"id\":1, \"name\":\"John\"}, {\"id\":2, \"name\":\"Jane\"}]";
        String actual = "[{\"id\":2, \"name\":\"Jane\"}, {\"id\":1, \"name\":\"John\"}]";

        try {
            JSONAssert.assertEquals(expected, actual, false); // Lenient comparison
            System.out.println("Arrays match in content.");
        } catch (AssertionError e) {
            System.out.println("Arrays do not match: " + e.getMessage());
        }
    }
}

Output:

Arrays match in content.

3. Partial Comparison

Sometimes, you may want to validate only specific fields in the JSON array. JSONAssert supports partial matching by excluding fields not present in the expected JSON.

Example:

import org.skyscreamer.jsonassert.JSONAssert;

public class JSONAssertPartialExample {
    public static void main(String[] args) {
        String expected = "[{\"id\":1}]";
        String actual = "[{\"id\":1, \"name\":\"John\"}, {\"id\":2, \"name\":\"Jane\"}]";

        try {
            JSONAssert.assertEquals(expected, actual, false); // Lenient comparison
            System.out.println("Partial comparison successful.");
        } catch (AssertionError e) {
            System.out.println("Partial comparison failed: " + e.getMessage());
        }
    }
}

Output:

Partial comparison successful.

Benefits of Using JSONAssert

  1. Simplicity: Directly compares JSON strings without additional libraries or parsing logic.
  2. Customizability: Choose strict or lenient comparison based on the test scenario.
  3. Integration: Works well with popular testing frameworks like JUnit and TestNG.

Common Pitfalls

  1. Whitespace Sensitivity: JSONAssert ignores whitespaces but will flag structural mismatches.
  2. Field Existence: Lenient mode will pass even if fields in the actual JSON are missing from the expected JSON.
  3. Array Order: Strict mode checks array order, while lenient mode does not, so use appropriately.

Followers