Table of contents
1.
Introduction👀
2.
What is Jackson API
3.
Class ObjectMapper👀
4.
Creating Objects🌐
4.1.
Create Object or ObjectNode🙋
4.1.1.
Example✨
4.2.
Create a Nested Object or ObjectNode🙋
4.2.1.
Example✨
5.
Creating Arrays🌐
5.1.
Create an Empty JSON Array🙋
5.2.
Create First JSON Object🙋
5.3.
Add created JSON Objects to JSON Array.🙋
6.
Frequently Asked Questions
6.1.
Is it possible to create arrays in JSON?
6.2.
Can an array start a JSON data object?
6.3.
Can JSON hold an array?
6.4.
What is the Jackson API used for?
6.5.
Do JSON arrays support multiple types?
7.
Conclusion
Last Updated: Mar 27, 2024
Medium

REST Assured – How To Create a JSON Object and array Using Jackson API – ObjectMapper(createObjectNode())

Author Mayank Goyal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction👀

In this article, we are going to create some new objects and arrays using jackson API with the help of the object mapper class. But do you know what Jackson API is? No worries! before directly diving into the topic, we will first see Jackson API. 

Jackson api

What is Jackson API

Jackson API is a high-performance JSON processor for Java. Jackson API allows us to do several things, like serialization, deserialization, reading, and writing to JSON files.

Jackson API must be added to the Java project build path. You can download a jar file with transitive jars or add it using Maven.

Now we have a basic understanding of the Jackson API. Now let's see how it can create objects and arrays.

Class ObjectMapper👀

Class ObjectMapper is the most powerful class provided by Jackson API. We will use the ObjectMapper class a maximum number of times. This class provides us with the functionalities of reading and writing JSON files.

object mapper

You will be using ObjectMapper class to create a JSON object or ObjectNode.

You can start with this familiar JSON payload which is created using ObjectMapper.🌟

{
  "firstname": "Mayank",
  "lastname": "Goyal",
  "totalfees": 100000,
  "depositpaid": true,
  "sessiondates": {
  "startdate": "2019-07-01",
  "enddate": "2023-07-01"
  }
}

 

As mentioned above, JSON is a nested JSON Object. The root node is one JSON object with fields like firstname, lastname, total fees, and deposit paid, while the session is another JSON object.

Creating Objects🌐

We create an object or object node using the method put in the ObjectMapper class of the Jackson API. 

Create Object or ObjectNode🙋

Jackson requires the use of the createObjectNode() function of the ObjectMapper class to create an instance of the ObjectNode class. The ObjectNode class provides overloaded methods called put(String fieldName, T fieldValue). Put method accepts values of many primitive and wrapper class types, including String, Boolean, etc., as field names. Field names should all be distinct. Duplicate field names will be overridden by the most current values rather than throwing an error. It is comparable to Java's Map's put() function.

Use the writeValueAsString() method provided by the ObjectMapper class to obtain the produced JSON Object as a string. Use the writerWithDefaultPrettyPrinter() method to prepare your JSON according to your specifications.

✴️Note: Please include this Maven Dependency:

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.0</version>
</dependency>


Let us understand it with the help of an example.

Example✨

Code🧑‍💻

package ninjas;


import org.testng.annotations.Test;
​import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.core.JsonProcessingException;
​
public class JSONusingJackson {
@Test
public void CreatingNestedJsonObjectTest() throws JsonProcessingException
{
/* Create an object to ObjectMapper*/
ObjectMapper ObjMap3r = new ObjectMapper();

/*Creating Node that maps to JSON Object structures in JSON content*/
ObjectNode application = ObjMap3r.createObjectNode();

/* PUT method - accepts many data types as field values.*/
​
/* String - field value*/
application.put("firstname", "Mayank");
application.put("lastname", "Goyal");
​
/* Integer - field value*/
application.put("totalfees", 100000);
​
/* Boolean - field value*/
application.put("depositpaid", true);
​
application.put("department", "CS");
​/* To print created JSON object*/
String createdPlainJsonObject = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(application);
System.out.println("Created plain JSON Object is : \n"+ createdPlainJsonObject);
                       }
}

 

Output📤

output

Create a Nested Object or ObjectNode🙋

The put(String fieldName, JsonNode fieldValue) method is no longer supported, making it impossible to create nested JSON objects or add another JSON object as a field value. We use set(String fieldName, JsonNode fieldValue) or replace (String fieldName, JsonNode fieldValue)

Example✨

Code🧑‍💻

package ninjas;


import org.testng.annotations.Test;
​import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.core.JsonProcessingException;
​
​
public class JSONusingJackson {
@Test
public void CreatingNestedJsonObjectTest() throws JsonProcessingException
{
/* Create an object to ObjectMapper*/
ObjectMapper ObjMap3r = new ObjectMapper();

/*Creating Node that maps to JSON Object structures in JSON content*/
ObjectNode application = ObjMap3r.createObjectNode();

/* PUT method - accepts many data types as field values.*/
​
/* String - field value*/
application.put("firstname", "Mayank");
application.put("lastname", "Goyal");
​
/* Integer - field value*/
application.put("totalfees", 100000);
​
/* Boolean - field value*/
application.put("depositpaid", true);
​
application.put("department", "CS");
​
/* To print created JSON object*/
String createdPlainJsonObject = ObjMap3r.writerWithDefaultPrettyPrinter().writeValueAsString(application);
System.out.println("Created plain JSON Object is : \n"+ createdPlainJsonObject);
​

/* We create a nested JSON Object*/
ObjectNode session = ObjMap3r.createObjectNode();
session.put("startdate", "2022-11-04");
session.put("enddate", "2022-11-05");

/* We use either set(String fieldName, JsonNode value) or replace(String fieldName, JsonNode value)*/
application.set("sessiondates", session);

/* To get the created JSON object as a string. Use writerWithDefaultPrettyPrinter() for proper formatting*/
String createdNestedJsonObject = ObjMap3r.writerWithDefaultPrettyPrinter().writeValueAsString(application);
​
System.out.println("Created nested JSON Object is : \n"+ createdNestedJsonObject);
​

}
}

 

Output📤

output

Now that you have learned how to create objects and nested objects using ObjectMapper class. In the next section, we will learn to create arrays using ObjectMapper class.

Creating Arrays🌐

We create an array or array node in the same process as creating an object or object node. We will use the same method put in the ObjectMapper class of the Jackson API. The basic syntax remains the same.

You can start with this familiar JSON Array payload created using ObjectMapper, as we did while creating objects.🌟

[
{
  "firstname": "Mayank",
  "lastname": "Goyal",
  "totalfees": 1,00,000,
  "depositpaid": true,
  "department" : "IT",
  "sessiondates": {
  "startdate": "2019-07-01",
  "enddate": "2023-07-01"
  }
},
{
  "firstname": "Debojeet",
  "lastname": "Jha",
  "totalfees": 5000,
  "depositpaid": true,
  "department" : "IT",
  "sessiondates": {
  "startdate": "2019-07-01",
  "enddate": "2023-07-01"
  }
}
]

 

The above payload is a JSON array containing two JSON objects.

✴️Note: Please include this Maven Dependency:

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.0</version>
</dependency>

 

Now, we will be creating an empty JSON array.

Create an Empty JSON Array🙋

We use the createArrayNode() function of the ObjectMapper class to create JSON arrays. createArrayNode() will return a reference of ArrayNode class.

Code🧑‍💻

ObjectMapper objectMapper = new ObjectMapper();

/* Create an array that will hold two JSON objects*/
ArrayNode parentArray = objectMapper.createArrayNode();

Create First JSON Object🙋

Code🧑‍💻

/* Create an object to ObjectMapper*/
ObjectMapper objectMapper = new ObjectMapper();

/*  Creating Node that maps to JSON Object structures in JSON content*/
ObjectNode firstapplication = objectMapper.createObjectNode();

/* Similar to the map put approach. The put method can accept too many data types as field values.*/


/* String as field value*/
firstapplication.put("firstname", "Mayank");
firstapplication.put("lastname", "Goyal");


/* integer as field value*/
firstapplication.put("totalfees", 100000);


/* boolean as field value*/
firstapplication.put("depositpaid", true);


firstapplication.put("department", "IT");


/* We create a nested JSON Object*/
ObjectNode firstsession = objectMapper.createObjectNode();
firstsession.put("startdate", "2021-07-01");
firstsession.put("enddate", "2021-07-01");

/*We use either set(String fieldName, JsonNode value) or replace(String fieldName, JsonNode value)*/
application.set("sessiondates", firstsession);

 

Similarly, create another JSON object.

Code🧑‍💻

ObjectNode secondapplication = objectMapper.createObjectNode();

/* Similar to the map put approach. The put method can accept too many data types as field values.*/


/*String as field value*/
secondapplication.put("firstname", "Debojeet");
secondapplication.put("lastname", "Jha");


/* integer as field value*/
secondapplication.put("totalfees", 5000);


/* boolean as field value*/
secondapplication.put("depositpaid", true);


secondapplication.put("department", "IT");


/* We create a nested JSON Object*/
ObjectNode secondsession = objectMapper.createObjectNode();
secondsession.put("startdate", "2021-07-01");
secondsession.put("enddate", "2021-07-01");

/* We use either set(String fieldName, JsonNode value) or replace(String fieldName, JsonNode value)*/
application.set("sessiondates", secondsession);

Add created JSON Objects to JSON Array.🙋

One JSON Object can be added to an array at a time using the add() method provided by the class ArrayNode. Use the addAll() function, which accepts a Collection<? extends JsonNode> to add several Object Nodes to an array simultaneously. Because List extends Collection, we can make a list of all JSON objects and add to it.

parentArray.add(firstapplication);
parentArray.add(secondapplication);
OR
parentArray.addAll(Arrays.asList(firstapplication,secondapplication));


✴️Note:- If you try to add duplicate Object Nodes, they will be added to the array.


Code🧑‍💻

/*To print created JSON array as a string with the proper format*/
StringjsonArrayAsString= =objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(parentArray);
System.out.println("Created JSON Array is : ");
System.out.println(jsonArrayAsString);


Complete Code🧑‍💻

package javaPackageName;


import java.util.Arrays;


import org.testng.annotations.Test;


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


public class JSONandNestedArray {
@Test
public void CreatingNestedJsonObjectTest() throws JsonProcessingException
{
/* Create an object to ObjectMapper*/
ObjectMapper objectMapper = new ObjectMapper();

/* Create an array that will hold two JSON objects*/
ArrayNode parentArray = objectMapper.createArrayNode();



/* Creating Node that maps to JSON Object structures in JSON content*/
ObjectNode firstapplication = objectMapper.createObjectNode();

/* Similar to the map put approach. The put method can accept too many data types as field values.*/


/* String as field value*/
firstapplication.put("firstname", "Mayank");
firstapplication.put("lastname", "Goyal");


/* integer as field value*/
firstapplication.put("totalfees", 100000);


/* boolean as field value
firstapplication.put("depositpaid", true);


firstapplication.put("department", "IT");


/*We create a nested JSON Object*/
ObjectNode firstsession = objectMapper.createObjectNode();
firstsession.put("startdate", "2021-07-01");
firstsession.put("enddate", "2021-07-01");

/* We use either set(String fieldName, JsonNode value) or replace(String fieldName, JsonNode value)*/
firstapplication.set("sessiondates", firstsession);

ObjectNode secondapplication = objectMapper.createObjectNode();

/* Similar to the map put approach. The put method can accept too many data types as field values.*/


/*String as field value*/
secondapplication.put("firstname", "Debojeet");
secondapplication.put("lastname", "Jha");


/*integer as field value*/
secondapplication.put("totalfees", 5000);


/* boolean as field value*/
secondapplication.put("depositpaid", true);


secondapplication.put("department", "IT");


/* We create a nested JSON Object*/
ObjectNode secondsession = objectMapper.createObjectNode();
secondsession.put("startdate", "2021-07-01");
secondsession.put("enddate", "2021-07-01");

/* We use either set(String fieldName, JsonNode value) or replace(String fieldName, JsonNode value)*/
secondapplication.set("sessiondates", secondsession);


parentArray.addAll(Arrays.asList(firstapplication,secondapplication));
        
/*To print created JSON array as a string with the proper format*/
String jsonArrayAsString =  objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(parentArray);
System.out.println("Created JSON Array is : ");
System.out.println(jsonArrayAsString);


}
}

 

Output📤

output

We hope you have understood how to create a JSON object and array using Jackson API – ObjectMapper(createObjectNode()).

Must Read Array of Objects in Java

Frequently Asked Questions

Is it possible to create arrays in JSON?

Yes, it is; by instantiating the JSONArray class, construct a JSON array and add elements to the array using the add() function of the JSONArray class.

Can an array start a JSON data object?

JSON text can begin with a square bracket (i.e., an array).

Can JSON hold an array?

Strings, numbers, booleans, objects, and other arrays can all be stored inside JSON. Commas must separate values in a JSON array. JSON arrays are very similar to JavaScript arrays.

What is the Jackson API used for?

Jackson is a high-performance JSON processor used for Java. It is the most popular library for serializing Java objects or Map to JSON and vice-versa. It is completely based on Java.

Do JSON arrays support multiple types?

Yes, in JSON, an array's elements could all be of a distinct type.

Conclusion

In this article, we learned about Jackson API and how we create arrays and objects using ObjectMapper class of Jackson API. Further, I provided some examples to help you understand the same. 

That's it from the article. I hope you all like it.

You can refer to similar articles for more information

 

Recommended problems -

 

You can refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, Javascript, System Design, etc. Enroll in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.

Live masterclass