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

My name is Amod Mahajan and I am an IT employee with 6+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went through so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning

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.

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

by Amod Mahajan time to read: 4 min
0
%d bloggers like this: