Javatpoint Logo
Javatpoint Logo

Compare JSON Objects with Jackson

Jackson is one of the most used libraries for comparing JSON objects. Many times, we need to compare two JSON objects to find whether both are the same or different from each other.

In order to use Jakcson for comparing JSON objects, we add the following dependency in our POM.xml file:

By using ObjectMapper class, we can compare:

  1. Two simple JSON Objects.
  2. Two JSON Objects with a nested element.
  3. Two JSON Objects containing a list element.

Let's first understand the comparison of a simple JSON object.

Suppose we have a JSON string which is defined as the jsonString1:

And, we need to compare it with another JSON string which is defined as jsonString2:

Let's take an example to understand how we can compare two simple JSON object by using Jackson:

CompareJSONObjectsExample1.java

Output:

Compare JSON Objects with Jackson

We use the same techniques for comparing the JSON Objects having nested elements or a list of elements.

Compare JSON Objects with Custom Comparator

The JsonNode.equals() method works fine for most of the cases in comparing two objects. However, Jackson provides one more variant of the equals() method, i.e., JsonNode.equals(comparator, JsonNode) for configuring the custom Java Comparator object.

So, we can also use this variant of the equals() method for comparing two JSON objects. Let's first create a custom comparator, and later on, we will use it for comparing two JSON objects in an example.

Note: Standard equals() method considers values 121 and 121.0 as different.

NameNodeComparator.java

CompareJSONObjectsExample2.java

Output:

Compare JSON Objects with Jackson
Next Topic#





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA