Compare JSON Objects Using JSONAssert Library

In software testing, verifying JSON responses is a common requirement, especially when testing RESTful APIs. Comparing JSON objects can be tricky because of potential variations in field order or nesting. This is where the JSONAssert library comes in handy. It simplifies JSON comparison by providing flexible options to assert JSON equality.

In this blog, we’ll explore how to use JSONAssert for comparing JSON objects effectively.

What is JSONAssert?

JSONAssert is a lightweight Java library for JSON comparisons. It provides methods to compare two JSON objects and assert their equality. Unlike simple string comparisons, JSONAssert intelligently handles JSON structures, ignoring insignificant differences such as field order.

Key Features:

  1. Order-agnostic comparison: Ignores the order of fields during comparison (optional).
  2. Customizable comparison: Allows strict or lenient assertions based on your requirements.
  3. Ease of use: Simple methods to validate JSON equality with meaningful error messages.

Adding JSONAssert to Your Project

To use JSONAssert, include the following dependency in your Maven pom.xml file:

<dependency>

    <groupId>org.skyscreamer</groupId>

    <artifactId>jsonassert</artifactId>

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

    <scope>test</scope>

</dependency>

Comparing JSON Objects

Basic Example

Here’s a simple example to compare two JSON strings:

import org.skyscreamer.jsonassert.JSONAssert;


public class JSONAssertExample {

    public static void main(String[] args) {

        String expected = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";

        String actual = "{\"city\":\"New York\",\"name\":\"John\",\"age\":30}";


        try {

            // Lenient comparison: ignores field order

            JSONAssert.assertEquals(expected, actual, false);

            System.out.println("JSONs are equal!");

        } catch (AssertionError e) {

            System.out.println("JSONs are not equal: " + e.getMessage());

        }

    }

}

Output:

JSONs are equal!

Strict vs Lenient Comparison

JSONAssert supports two modes of comparison:

  1. Strict Mode: Fields must match in order and content.
  2. Lenient Mode: Ignores the order of fields.

Example:

public class StrictLenientComparison {
    public static void main(String[] args) {
        String expected = "{\"name\":\"John\",\"age\":30}";
        String actual = "{\"age\":30,\"name\":\"John\"}";

        try {
            // Strict comparison
            JSONAssert.assertEquals(expected, actual, true);
        } catch (AssertionError e) {
            System.out.println("Strict mode failed: " + e.getMessage());
        }

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

Output:

Strict mode failed: Expected name:John at name
Lenient mode passed!

Ignoring Fields

JSONAssert does not natively support ignoring specific fields during comparison, but you can preprocess the JSON strings by removing unwanted fields.

Here’s an example:

import org.json.JSONObject;


public class IgnoreFieldsExample {

    public static void main(String[] args) {

        String expected = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";

        String actual = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\",\"country\":\"USA\"}";


        // Remove 'country' field from the actual JSON

        JSONObject actualJson = new JSONObject(actual);

        actualJson.remove("country");


        try {

            JSONAssert.assertEquals(expected, actualJson.toString(), false);

            System.out.println("JSONs are equal after ignoring fields!");

        } catch (AssertionError e) {

            System.out.println("JSONs are not equal: " + e.getMessage());

        }

    }

}

Handling Nested JSON Objects

JSONAssert also handles nested JSON structures effectively:

public class NestedJsonComparison {

    public static void main(String[] args) {

        String expected = "{\"user\":{\"name\":\"John\",\"age\":30},\"status\":\"active\"}";

        String actual = "{\"status\":\"active\",\"user\":{\"age\":30,\"name\":\"John\"}}";


        try {

            JSONAssert.assertEquals(expected, actual, false);

            System.out.println("Nested JSONs are equal!");

        } catch (AssertionError e) {

            System.out.println("Nested JSONs are not equal: " + e.getMessage());

        }

    }

}

Advantages of JSONAssert

  1. Reduces complexity: Simplifies JSON comparisons, especially for API testing.
  2. Readable assertions: Provides clear error messages to debug mismatches.
  3. Integration-friendly: Works seamlessly with testing frameworks like JUnit and TestNG.

Limitations

  1. No field ignoring: Requires preprocessing to exclude specific fields.
  2. No custom comparators: Does not support custom comparison logic for certain fields.

Followers