Java
JSON
Object Comparison
Equality Test
Order Ignorance

Testing two JSON objects for equality ignoring child order in Java

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Testing for equality between two JSON objects in Java can be a straightforward task using various libraries; however, the complexity increases when the order of child objects within the JSON doesn’t matter. This involves a deep comparison where two JSON objects are considered equal if they contain the same set of name/value pairs, but not necessarily in the same order.

Understanding JSON Object

A JSON object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

Issues with Native Java Comparison

Java's native data structures like HashMap or LinkedHashMap do not directly support this kind of unordered or non-sequential comparison without customization. These structures treat JSON objects like normal strings or Maps. Specifically, the order of insertion affects equality and hash code generation in most Map implementations, which isn't ideal for comparing JSON objects where the order of elements doesn't matter.

Libraries for JSON Comparison

Several Java libraries can help in comparing JSON objects by ignoring the child order:

  • Jackson
  • Gson
  • org.json
  • JsonAssert

Jackson and Gson

Both Jackson and Gson provide ways to parse JSON into a Java representation that can be easily manipulated and compared. By converting JSON objects into Map objects, we can leverage these libraries to compare JSON by contents rather than by sequence.

Using Jackson

Here's how you could compare two JSON objects using Jackson, with an emphasis on ignoring child order:

java
1import com.fasterxml.jackson.databind.ObjectMapper;
2
3public boolean compareJsonObjects(String json1, String json2) throws Exception {
4    ObjectMapper mapper = new ObjectMapper();
5
6    Map<String, Object> map1 = mapper.readValue(json1, new TypeReference<Map<String, Object>>() {});
7    Map<String, Object> map2 = mapper.readValue(json2, new TypeReference<Map<String, Object>>() {});
8
9    return map1.equals(map2);
10}

Using Gson

Gson can be used similarly:

java
1import com.google.gson.Gson;
2import java.lang.reflect.Type;
3import com.google.gson.reflect.TypeToken;
4import java.util.Map;
5
6public boolean compareJsonObjects(String json1, String json2) {
7    Gson gson = new Gson();
8    Type type = new TypeToken<Map<String, Object>>() {}.getType();
9
10    Map<String, Object> map1 = gson.fromJson(json1, type);
11    Map<String, Object> map2 = gson.fromJson(json2, type);
12
13    return map1.equals(map2);
14}

JsonAssert

JsonAssert is a library that offers a sophisticated set of assertions specifically for JSON, allowing for more readable and tailor-made assertions that fit JSON structures, including the ability to ignore the order of array items and object fields.

java
1import org.skyscreamer.jsonassert.JSONAssert;
2
3public void compareJsonObjects(String json1, String json2) {
4    JSONAssert.assertEquals(json1, json2, JSONCompareMode.LENIENT);
5}

JSONCompareMode.LENIENT mode allows you to compare two JSON objects irrespective of the order.

Summary Table

FeatureJackson & GsonJsonAssert
Parses JSONYesYes
Order insensitive comparisonManual Map usageBuilt-in
Customizable comparison strategiesVia configurationVia modes
Dependency sizeMedium-LargeSmall
Ease of integrationModerateHigh

Summary

Utilizing the correct tools and libraries can greatly simplify the task of comparing JSON objects in Java. Depending on the complexity of the JSON objects and the specific requirements (like performance considerations or additional features), different libraries and methods might be more suitable. For most applications where child order in JSON objects should be ignored during comparison, JsonAssert provides an easy and robust solution, whereas Jackson and Gson offer more control and integration with broader JSON processing code if needed. Whether you choose a Map-based method with Jackson or Gson, or an assertion-based approach with JsonAssert, Java offers robust solutions to fit varied development needs.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions