Make Selenium Easy

REST Assured Tutorial 68 – Compare Two JSON using Jackson – Java Library

Introduction

As a part of the End to End REST Assured Tutorial, in this post, we will learn to compare two JSON using the Jackson library.

We may need to compare two JSON during API testing. For example – If we are going to get the same JSON response for an API every time or some parts of the response are always constant then instead of writing some logic to assert them, we can directly compare with an existing JSON response.

We have a couple of good Java libraries to do. In this post, we will use Jackson Library to compare two JSON responses.

Required Dependency

JsonNode equals() method

An abstract class JsonNode provided by Jackson API provides an abstract method called equals() which can be used to compare node objects. Equality for node objects is defined as a full (deep) value equality. This means that it is possible to compare complete JSON trees for equality by comparing the equality of root nodes. equals() method is an abstract method and implemented by ObjectNode and ArrayNode classes.

We need to convert the given JSON to JsonNode ( or ObjectNode or ArrayNode) first and then we can call the equals method on it.

Important points to be noted

  1. The above method will return true if JSON nodes are equal.
  2. The order of root elements in JSON nodes will not matter.
  3. The order of elements in the JSON array will matter and it will not be the same.

Example Programs

Compare JSON Objects

Output

Compare JSON Arrays

Output

You can download/clone the above sample project from here.

You can subscribe to my YouTube channel RetargetCommon to learn from video tutorials.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappyLearning

Find all Selenium related posts here, all API manual and automation related posts here, and find frequently asked Java Programs here.

Many other topics you can navigate through the menu.

Author: Amod Mahajan

A software Tester who is paid to judge products developed by others. Currently getting paid in American Dollars. Writing technical posts and creating YouTube videos are my hobbies.

1 thought on “REST Assured Tutorial 68 – Compare Two JSON using Jackson – Java Library

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.