REST Assured Tutorial 27 – How To Create JSON Array Using Jackson API – ObjectMapper – CreateArrayNode()

As a part of End to End REST Assured Tutorial , in this post We will learn to Create JSON Array using Jackson API’s class ObjectMapper.

We have already learnt to create JSON Object using Jackson API here.

About Jackson API

Jackson API is a high performance JSON processor for Java. We can perform serialization, deserialization , reading a JSON file, writing a JSON file and a lot more things using Jackson API.

To use Jackson API, we need to add it in java project build path. You can add using Maven or download a jar file with transitive jars.

Maven Dependency

Always try to use latest dependency from Central Maven Repository. I will use below dependency at the time of writing this post.



    com.fasterxml.jackson.core
    jackson-databind
    2.11.0

Note :- When we add jackosn-databind dependency then it will automatically download transitive dependencies of same version i.e. jackson-annotations and jackson-core as well.

If you download and add jackson-databind jar to build path, do not forget to download other two transitive dependencies as well.

Class ObjectMapper

This is the most powerful class provided by Jackson API and maximum time we will use this class. As of now just know that ObjectMapper provides functionalities for reading and writing JSON. We will learn more about it as we proceed further.

We will use Class ObjectMapper to create a JSON Array or ArrayNode.

Let’s start with our familiar JSON Array payload which we will create using ObjectMapper.

[
   {
      "firstname":"Jim",
      "lastname":"Brown",
      "totalprice":111,
      "depositpaid":true,
      "additionalneeds":"Breakfast",
      "bookingdates":{
         "checkin":"2021-07-01",
         "checkout":"2021-07-01"
      }
   },
   {
      "firstname" : "Amod",
      "lastname" : "Mahajan",
      "totalprice" : 222,
      "depositpaid" : true,
      "additionalneeds" : "Breakfast",
      "bookingdates" : {
         "checkin" : "2022-07-01",
         "checkout" : "2022-07-01"
     }
  }
]

Above JSON payload is a JSON array which holds two JSON Objects. Out approach will be :-

  1. Create an empty JSON Array.
  2. Create first JSON Object
  3. Create second JSON Object
  4. Add created JSON Objects to JSON Array

Create an empty JSON Array

To create a JSON Object we used createObjectNode() method of ObjectMapper class. Similarly to create JSON Array we use createArrayNode() method of ObjectMapper class. createArrayNode() will return reference of ArrayNode class.

Note :- Return type of createArrayNode() or createObjectNode() is co-variant. We will see this concept later.

ObjectMapper objectMapper = new ObjectMapper();
		
// Create an array which will hold two JSON objects
ArrayNode parentArray =  objectMapper.createArrayNode();

Create first JSON Object

We already know how to create JSON object using Jackson API.

// Creating Node that maps to JSON Object structures in JSON content
		ObjectNode firstBookingDetails = objectMapper.createObjectNode();
		
// It is similar to map put method. put method is overloaded to accept different types of data
// String as field value
firstBookingDetails.put("firstname", "Jim");
firstBookingDetails.put("lastname", "Brown");
// integer as field value
firstBookingDetails.put("totalprice", 111);
// boolean as field value
firstBookingDetails.put("depositpaid", true);
firstBookingDetails.put("additionalneeds", "Breakfast");
		
// Since requirement is to create a nested JSON Object
ObjectNode firstBookingDateDetails = objectMapper.createObjectNode();
firstBookingDateDetails.put("checkin", "2021-07-01");
firstBookingDateDetails.put("checkout", "2021-07-01");
		
// Since 2.4 , put(String fieldName, JsonNode value) is deprecated. So use either set(String fieldName, JsonNode value) or replace(String fieldName, JsonNode value)
firstBookingDetails.set("bookingdates", firstBookingDateDetails);

Create second JSON Object

// Creating Node that maps to JSON Object structures in JSON content
ObjectNode secondBookingDetails = objectMapper.createObjectNode();
// It is similar to map put method. put method is overloaded to accept different types of data
// String as field value
secondBookingDetails.put("firstname", "Amod");
secondBookingDetails.put("lastname", "Mahajan");
// integer as field value
secondBookingDetails.put("totalprice", 222);
// boolean as field value
secondBookingDetails.put("depositpaid", true);
secondBookingDetails.put("additionalneeds", "Breakfast");
		
// Since requirement is to create a nested JSON Object
ObjectNode secondBookingDateDetails = objectMapper.createObjectNode();
secondBookingDateDetails.put("checkin", "2022-07-01");
secondBookingDateDetails.put("checkout", "2022-07-01");
		
// Since 2.4 , put(String fieldName, JsonNode value) is deprecated. So use either set(String fieldName, JsonNode value) or replace(String fieldName, JsonNode value)
secondBookingDetails.set("bookingdates", secondBookingDateDetails);

Add created JSON Objects to JSON Array

Class ArrayNode provides a method add() which can add one JSON Object to array at a time.

parentArray.add(firstBookingDetails);
parentArray.add(secondBookingDetails);

To add multiple Object Nodes to array at a time we can use addAll() method which accepts a Collection<? extends JsonNode> . We can create a List (because List extends Collection)of all JSON Objects and add.

parentArray.addAll(Arrays.asList(firstBookingDetails,secondBookingDetails));

Note:- If you try to add duplicate Object Nodes, it will be added to array.

To print created JSON array as string with proper format

String jsonArrayAsString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(parentArray);
System.out.println("Created Json Array is : ");
System.out.println(jsonArrayAsString);

That’s all. We have created a JSON Array successfully using Jackson API.

Let’s learn some retrieving and manipulation methods.

Retrieving JSON Object from JSON array using index

Since JSON Array is iterable, we can retrieve a JSON object using its index.

// To get json array element using index
JsonNode firstElement = parentArray.get(0);
System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(firstElement));

Get size of JSON Array

size() method can be used to get size of JSON Array.

int sizeOfArray = parentArray.size();
System.out.println("Size of array is "+sizeOfArray);

Iterate JSON Array

iterator() method can be used to iterate through a JSON Array.

// To iterate JSON Array
Iterator iteraor = parentArray.iterator();
System.out.println("Prining Json Node using iterator : ");
while(iteraor.hasNext())
{
	JsonNode currentJsonNode = iteraor.next();
			System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(currentJsonNode));
}

Remove a JSON Object from JSON Array

We can remove a JSON object from JSON Array using its index.

// To remove an element from array
parentArray.remove(0);
System.out.println("After removing first element from array : "+ objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(parentArray));

Empty JSON Array

// To empty JSON Array
parentArray.removeAll();
System.out.println("After removing all elements from array : "+ objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(parentArray));

Complete Program

package JacksonAPIUsage;

import java.util.Arrays;
import java.util.Iterator;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

/*
 * [
   {
      "firstname":"Jim",
      "lastname":"Brown",
      "totalprice":111,
      "depositpaid":true,
      "additionalneeds":"Breakfast",
      "bookingdates":{
         "checkin":"2021-07-01",
         "checkout":"2021-07-01"
      }
   },
   {
      "firstname":"Amod",
      "lastname":"Mahajan",
      "totalprice":222,
      "depositpaid":true,
      "additionalneeds":"Lunch",
      "bookingdates":{
         "checkin":"2022-07-01",
         "checkout":"2022-07-01"
      }
   }
]
 * 
 */

public class CreateJsonArrayUsingJacksonAPI {
	
	public static void main(String[] args) throws JsonProcessingException {
		
		ObjectMapper objectMapper = new ObjectMapper();
		
		// Create an array which will hold two JSON objects
		ArrayNode parentArray =  objectMapper.createArrayNode();
		
		// Creating Node that maps to JSON Object structures in JSON content
		ObjectNode firstBookingDetails = objectMapper.createObjectNode();
		
		// It is similar to map put method. put method is overloaded to accept different types of data
		// String as field value
		firstBookingDetails.put("firstname", "Jim");
		firstBookingDetails.put("lastname", "Brown");
		// integer as field value
		firstBookingDetails.put("totalprice", 111);
		// boolean as field value
		firstBookingDetails.put("depositpaid", true);
		firstBookingDetails.put("additionalneeds", "Breakfast");
		
		// Since requirement is to create a nested JSON Object
		ObjectNode firstBookingDateDetails = objectMapper.createObjectNode();
		firstBookingDateDetails.put("checkin", "2021-07-01");
		firstBookingDateDetails.put("checkout", "2021-07-01");
		
		// Since 2.4 , put(String fieldName, JsonNode value) is deprecated. So use either set(String fieldName, JsonNode value) or replace(String fieldName, JsonNode value)
		firstBookingDetails.set("bookingdates", firstBookingDateDetails);
		
		
		// Creating Node that maps to JSON Object structures in JSON content
		ObjectNode secondBookingDetails = objectMapper.createObjectNode();
		
		// It is similar to map put method. put method is overloaded to accept different types of data
		// String as field value
		secondBookingDetails.put("firstname", "Amod");
		secondBookingDetails.put("lastname", "Mahajan");
		// integer as field value
		secondBookingDetails.put("totalprice", 222);
		// boolean as field value
		secondBookingDetails.put("depositpaid", true);
		secondBookingDetails.put("additionalneeds", "Breakfast");
		
		// Since requirement is to create a nested JSON Object
		ObjectNode secondBookingDateDetails = objectMapper.createObjectNode();
		secondBookingDateDetails.put("checkin", "2022-07-01");
		secondBookingDateDetails.put("checkout", "2022-07-01");
		
		// Since 2.4 , put(String fieldName, JsonNode value) is deprecated. So use either set(String fieldName, JsonNode value) or replace(String fieldName, JsonNode value)
		secondBookingDetails.set("bookingdates", secondBookingDateDetails);
		
		
		parentArray.add(firstBookingDetails);
		parentArray.add(secondBookingDetails);
		
		// OR
		parentArray.addAll(Arrays.asList(firstBookingDetails,secondBookingDetails));
		
		String jsonArrayAsString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(parentArray);
		System.out.println("Created Json Array is : ");
		System.out.println(jsonArrayAsString);
		System.out.println("=======================================================================================");
		// To get json array element using index
		JsonNode firstElement = parentArray.get(0);
		System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(firstElement));
		System.out.println("=======================================================================================");
		// To get size of JSON array
		int sizeOfArray = parentArray.size();
		System.out.println("Size of array is "+sizeOfArray);
		System.out.println("=======================================================================================");
		// To iterate JSON Array
		Iterator iteraor = parentArray.iterator();
		System.out.println("Prining Json Node using iterator : ");
		while(iteraor.hasNext())
		{
			JsonNode currentJsonNode = iteraor.next();
			System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(currentJsonNode));
		}
		System.out.println("=======================================================================================");
		// To remove an element from array
		parentArray.remove(0);
		System.out.println("After removing first element from array : "+ objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(parentArray));
		System.out.println("=======================================================================================");
		// To empty JSON Array
		parentArray.removeAll();
		System.out.println("After removing all elements from array : "+ objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(parentArray));
			
	}

}

Output

Created Json Array is : 
[ {
  "firstname" : "Jim",
  "lastname" : "Brown",
  "totalprice" : 111,
  "depositpaid" : true,
  "additionalneeds" : "Breakfast",
  "bookingdates" : {
    "checkin" : "2021-07-01",
    "checkout" : "2021-07-01"
  }
}, {
  "firstname" : "Amod",
  "lastname" : "Mahajan",
  "totalprice" : 222,
  "depositpaid" : true,
  "additionalneeds" : "Breakfast",
  "bookingdates" : {
    "checkin" : "2022-07-01",
    "checkout" : "2022-07-01"
  }
}, {
  "firstname" : "Jim",
  "lastname" : "Brown",
  "totalprice" : 111,
  "depositpaid" : true,
  "additionalneeds" : "Breakfast",
  "bookingdates" : {
    "checkin" : "2021-07-01",
    "checkout" : "2021-07-01"
  }
}, {
  "firstname" : "Amod",
  "lastname" : "Mahajan",
  "totalprice" : 222,
  "depositpaid" : true,
  "additionalneeds" : "Breakfast",
  "bookingdates" : {
    "checkin" : "2022-07-01",
    "checkout" : "2022-07-01"
  }
} ]
=======================================================================================
{
  "firstname" : "Jim",
  "lastname" : "Brown",
  "totalprice" : 111,
  "depositpaid" : true,
  "additionalneeds" : "Breakfast",
  "bookingdates" : {
    "checkin" : "2021-07-01",
    "checkout" : "2021-07-01"
  }
}
=======================================================================================
Size of array is 4
=======================================================================================
Prining Json Node using iterator : 
{
  "firstname" : "Jim",
  "lastname" : "Brown",
  "totalprice" : 111,
  "depositpaid" : true,
  "additionalneeds" : "Breakfast",
  "bookingdates" : {
    "checkin" : "2021-07-01",
    "checkout" : "2021-07-01"
  }
}
{
  "firstname" : "Amod",
  "lastname" : "Mahajan",
  "totalprice" : 222,
  "depositpaid" : true,
  "additionalneeds" : "Breakfast",
  "bookingdates" : {
    "checkin" : "2022-07-01",
    "checkout" : "2022-07-01"
  }
}
{
  "firstname" : "Jim",
  "lastname" : "Brown",
  "totalprice" : 111,
  "depositpaid" : true,
  "additionalneeds" : "Breakfast",
  "bookingdates" : {
    "checkin" : "2021-07-01",
    "checkout" : "2021-07-01"
  }
}
{
  "firstname" : "Amod",
  "lastname" : "Mahajan",
  "totalprice" : 222,
  "depositpaid" : true,
  "additionalneeds" : "Breakfast",
  "bookingdates" : {
    "checkin" : "2022-07-01",
    "checkout" : "2022-07-01"
  }
}
=======================================================================================
After removing first element from array : [ {
  "firstname" : "Amod",
  "lastname" : "Mahajan",
  "totalprice" : 222,
  "depositpaid" : true,
  "additionalneeds" : "Breakfast",
  "bookingdates" : {
    "checkin" : "2022-07-01",
    "checkout" : "2022-07-01"
  }
}, {
  "firstname" : "Jim",
  "lastname" : "Brown",
  "totalprice" : 111,
  "depositpaid" : true,
  "additionalneeds" : "Breakfast",
  "bookingdates" : {
    "checkin" : "2021-07-01",
    "checkout" : "2021-07-01"
  }
}, {
  "firstname" : "Amod",
  "lastname" : "Mahajan",
  "totalprice" : 222,
  "depositpaid" : true,
  "additionalneeds" : "Breakfast",
  "bookingdates" : {
    "checkin" : "2022-07-01",
    "checkout" : "2022-07-01"
  }
} ]
=======================================================================================
After removing all elements from array : [ ]

Passing ArrayNode or JSON Array to request is similar to ObjecNode or JSON object which we have learnt here.

You can download/clone above sample project from here.

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 post here, all API manual and automation related posts here and find frequently asked Java Programs here.

Many other topics you can navigate through menu.

2 thoughts on “REST Assured Tutorial 27 – How To Create JSON Array Using Jackson API – ObjectMapper – CreateArrayNode()

Leave a Reply

Your email address will not be published. Required fields are marked *