Do you think IIT Guwahati certified course can help you in your career?
No
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.
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.
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.🌟
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.
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📤
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📤
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.🌟
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📤
We hope you have understood how to create a JSON object and array using Jackson API – ObjectMapper(createObjectNode()).
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