Table of contents
1.
Introduction
2.
Need of JSON Comparison
3.
JSONassert Library 
3.1.
Example
4.
Compare Parts Of JSON Objects
4.1.
Example
4.2.
Code Implementation
4.2.1.
Output
5.
Compare Parts Of JSON Arrays
5.1.
Example
5.2.
Code Implementation
5.2.1.
Output
6.
Ignore Fields From JSON For Comparison
6.1.
Ignoring Fields In JSON Object
6.2.
Ignoring Fields In JSON Arrays
7.
Frequently Asked Questions
7.1.
What is REST API Testing?
7.2.
What is JSON?
7.3.
Are REST assured and REST API the same?
7.4.
Why is JSON used over XML?
7.5.
Which is better, postman or rest assured?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

REST Assured - How To Compare Part of JSON Objects and Arrays using JSONassert library

Introduction

Hello ninjas, Sometimes we compare portions of an object like the tires of a car to figure out which one needs replacement; we need to compare parts of JSON data for similar purposes. 

REST Assured – How To Compare Part Of JSON Objects And Arrays Using JSONassert Library

In this article, we will learn how to compare parts of JSON objects using the JSONassert library. We will also learn how to compare parts of JSON arrays using the JSONassert library in REST assured. If you are new to REST assured, refer to introduction to REST assured.

Need of JSON Comparison

Let’s learn some essential concepts first,

JSON objects contain key-value pairs. It is surrounded by curly brackets { }. It is written in “ Key: value “ format.

Similar types of JSON objects are stored in JSON arrays. It is represented by straight brackets [ ].

We need to compare parts of JSON objects or JSON arrays: 

  •  To check if data dependencies are relevant.
     
  •  To check if the JSON data format is correct or not.
     
  •  To check the presence of particular data.
     
  •  To prevent errors in the JSON data.
     
  •  To check new updates in the data.

JSONassert Library 

JSONassert library is a Java library that helps to implement JSON equality. We can use it to compare parts of JSON arrays using the JSONassert library in REST assured. It is also used to compare parts of JSON Objects using the JSONassert library in REST assured.

Example

A JSON array - [1,2,3,4] & [4,3,2,1]
Here, the JSONassert library will tell the user if the given arrays are similar or not. It compares JSON with the existing JSON response in REST assured. This decreases the programmer's workload, and they don’t have to write several statements/logic to complete a few tasks.

JSONassert library provides two ways to check equality : 

  • assertEquals() method - compare parts of JSON objects and JSON arrays.
     
  • JSONcomparemode - provides four different modes with different behaviors for JSON comparison. 

    A. Strict 
    B. Lenient 
    C. Non-extensible 
    D. Strict Order

Compare Parts Of JSON Objects

As discussed above, we need to compare parts of JSON Objects using the JSONassert library in REST assured for a few essential reasons

We will use both methods mentioned in the “JSONassert library” section to compare parts of JSON objects using the JSONassert library in REST assured in the given an example.

Example

JSON Object 1

{
  "firstName": "Anchita",
  "lastName": “Sharma",
  "address":{
   			"city": "Mumbai",
    		"state": "Maharashtra"
  }
}


JSON Object 2

{
  "firstName": "Anchita",
  "lastName": "Sharma",
  "temporaryaddress": {
     	"city": "Mumbai",
   		"state": "Maharashtra"
  }
}


We will use JSONpath and JSONassert library methods in REST assured to compare parts of JSON objects using the JSONassert library in REST assured.

Code Implementation

package ComparePortionOfJson;
 
import org.json.JSONException;
import org.json.JSONObject;
import org.skyscreamer.jsonassert.JSONAssert;
import org.skyscreamer.jsonassert.JSONCompareMode;
 
public class ComparePortionOfJsonObjects {

	public static void main(String[] args) throws JSONException {

		JSONObject jsonObject1 = new JSONObject("{\r\n" +
									"  \"firstName\": \"Anchita\",\r\n" +
									"  \"lastName\": \"Sharma\",\r\n" +
									"  \"address\": {\r\n" +
									"    \"city\": \"Mumbia\",\r\n" +
									"    \"state\": \"Maharashtra\"\r\n" +
									"  }\r\n" +
									"}");
		JSONObject jsonObject2 = new JSONObject("{\r\n" +
									"  \"firstName\": \"Anchita\",\r\n" +
									"  \"lastName\": \"Sharma\",\r\n" +
									"  \"temporaryaddress\": {\r\n" +
									"    \"city\": \"Mumbai\",\r\n" +
									"    \"state\": \"Maharashtra\"\r\n" +
									"  }\r\n" +
									"}");

// We will assert address objects similarity in both JSON Objects
// We need to use getJSONObject() method as both address fields are JSON Objects 
		JSONAssert.assertEquals(
			jsonObject1.getJSONObject("address"), 
			jsonObject2.getJSONObject("temporaryaddress"), 
			JSONCompareMode.LENIENT
		);
   }
}

Output

output image

Since “address” and “temporaryaddress” keys have the same values, thus when compared, JSON will pass.

To compare parts of JSON Objects using the JSONassert library in REST assured, We compared the “address” fields of JSON Object 1 to the “temporaryaddress” field of JSON Object 2 in REST assured.

Compare Parts Of JSON Arrays

To compare parts of JSON arrays using the JSONassert library in REST assured, we use the index of JSON arrays.

Example

JSON array 1

[
  {
    "id": 1,
    "firstname": "Anchita",
    "lastname": "Sharma"
  },
  {
    "id": 2,
    "firstname": "Anshit",
    "lastname": "Singh"
  }
]


JSON array 2

[
  {
    "id": 1,
    "firstname": "Anchita",
    "lastname": "Sharma"
  },
  {
    "id": 2,
    "first_name": "Stuti",
    "last_name": "Jain"
  }
]


To compare parts of JSON arrays using the JSONassert library in REST assured. We will compare parts of JSON objects at the first index of both JSON arrays. We will use both the comparison methods of the JSONassert library. 

Code Implementation

package ComparePortionOfJson;
 
import org.json.JSONArray;
import org.json.JSONException;
import org.skyscreamer.jsonassert.JSONAssert;
import org.skyscreamer.jsonassert.JSONCompareMode;
 
public class ComparePortionOfJsonArrays {

	public static void main(String[] args) throws JSONException {

			JSONArray jSONArray1 = new JSONArray("[\r\n" +
										"  {\r\n" +
										"    \"id\": 1,\r\n" +
										"    \"firstname\": \"Anchita\",\r\n" +
										"    \"lastname\": \"Sharma\"\r\n" +
										"  },\r\n" +
										"  {\r\n" +
										"    \"id\": 2,\r\n" +
										"    \"firstname\": \"Anshit\",\r\n" +
										"    \"lastname\": \"Singh\"\r\n" +
										"  }\r\n" +
										"]");

			JSONArray jSONArray2 = new JSONArray("[\r\n" +
										"  {\r\n" +
										"    \"id\": 1,\r\n" +
										"    \"firstname\": \"Anchita\",\r\n" +
										"    \"lastname\": \"Sharma\"\r\n" +
										"  },\r\n" +
										"  {\r\n" +
										"    \"id\": 2,\r\n" +
										"    \"firstname\": \"Stuti\",\r\n" +
										"    \"lastname\": \"Jain\"\r\n" +
										"  }\r\n" +
										"]");

// We will assert first index of both JSON arrays 
// Since index elements in both arrays are JSON objects so we will use getJSONObject method 
			JSONAssert.assertEquals(JSONArray1.getJSONObject(0), 
				JSONArray2.getJSONObject(0), 
				JSONCompareMode.LENIENT
			);
   }
}

Output

output image

Since we are comparing objects at the first index of both arrays, which is the “Id” key, and both the keys have the same value “1” , JSON will pass.  

We compared the “Id" elements of JSON objects in both JSON arrays to compare parts of JSON arrays using the JSONassert library in REST assured. You can also compare the same types of JSON objects to JSON arrays using the JSONassert library methods.

Ignore Fields From JSON For Comparison

We need to ignore some elements or fields to effectively compare parts of JSON objects using the JSONassert library in REST assured or to compare parts of JSON arrays using the JSONassert library in REST assured. We might also want to ignore a few fields that are not similar to compare desired fields.

We use JSONcomparator for this purpose.
We can not directly use the JSONcomparator. Instead, we use classes provided by it to implement the comparator indirectly.

  • Customcomparator - It contains 2 parameters: JSONCompareMode and collection of customization array.

Syntax:

CustomComparator(JSONCompareMode.<mode name>, Customization(“<array elements>”));

 

  • Customization - consists of elements or fields to be ignored in the form of an array.

Syntax:

Customization(“<field1>”, (<O1>, <O2>) -&gt ; true);


NOTE: &gt and O1,O2 are lambda expressions in Java. These represent the values in the field. We no longer need to fetch the value by scanning the JSON data files if we use these expressions.

How do we ignore a field?
We choose a field and provide its different values. Then we default to set it to true using the classes provided by JSONcomparator.

Ignoring Fields In JSON Object

The ways for ignoring fields for simple and nested JSON objects are the same.
We use the CustomComparator and customization class. 

Syntax

JSON Comparator <name> = 
	new CustomComparator(
		JSONCompareMode.<mode name>, 
		new Customization(“<field name>”, 
		(O1,O2) -&gt; true)
		);

JSONasset.assertequals(
	<string1 name>,
	<string2 name>,
	<comparator name>
	);


We usually use the lenient mode of JSONCompareMode for ignoring fields in JSON objects.

Ignoring Fields In JSON Arrays

The ways for ignoring fields for simple and nested JSON arrays are the same.
We use the CustomComparator and customization class. 

Syntax

JSON Comparator <name> = 
	new CustomComparator(
	JSONCompareMode.STRICT, 
	new Customization(
		“[<index number>].<field name>”, 
		(O1,O2) -&gt; true)
	);

JSONasset.assertequals(<string1 name>,
	<string2 name>,
	<comparator name>
	);


Notice that the mode “JSONCompareMode" for ignoring fields in JSON array is fixed to STRICT. This is because we are comparing specific indexes in JSON arrays that cannot be executed through any other mode.

Let's discuss some FAQs.

Must Read Array of Objects in Java

Frequently Asked Questions

What is REST API Testing?

An open-source method for testing RESTful APIs for web applications is called REST API testing. It is mainly used to test web applications that use JSON and XML. All procedures are compatible, including GET, PUT, POST, PATCH, and DELETE. In Java, the REST API is a library.

What is JSON?

JSON is a free and open-source file format and data exchange format that uses text humans can read to store and send data objects made up of arrays and attribute-value pairs.

Are REST assured and REST API the same?

A Java library called REST Assured is used to test RESTful APIs. It is frequently used to test web applications that handle JSON and XML. Additionally, it supports all RESTful methods, including PUT, GET, PATCH, POST, and DELETE.

Why is JSON used over XML?

JSON is designed for data interchange. Thus it is faster than XML. Moreover, JSON can be parsed by a javascript function. At the same time, XML requires an XML parser.

Which is better, postman or rest assured?

Rest assured is better than the postman. Rest assured, you can reuse code as it is a Java client. Moreover, in postman, we can provide only one data file for each collection, unlike rest assured.

Conclusion

This article discussed the need for a comparison of JSON data. We learned about the JSONassert library and how to use it to compare parts of JSON objects using the JSONassert library in REST assured and to compare parts of JSON arrays. We also learned different ways to ignore fields in JSON objects and arrays as needed.

To learn more about REST assured, refer to,

Recommended problems -

 

Please refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. And also, enroll in our courses and refer to the mock test and problems available. Have a look at the interview experiences and interview bundle for placement preparations.

Happy Learning!

Live masterclass