As a part of End to End REST Assured Tutorial, in this post, We will learn the “Serializaion” concept where we will create JSON Object or Payload from Java Objects for APIs.
We have learned about POJOs in the previous posts. If you have not refereed those posts then I will advise you to go through about POJO concepts here:-
What Is Plain Old Java Object (POJO)?
How To Create POJO Classes Of A JSON Object Payload?
How To Create POJO Classes Of A JSON Array Payload?
How To Create POJO Classes Of A Nested JSON Payload?
Now we will learn how to create JSON objects using POJOs. To create a JSON object (JSON) from Java Objects( POJOs) is called Serialization. For this, we can use any JSON parser APIs. In this post, we will use Jackosn APIs which is more famous. I will also cover using the GSON library later.
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 to the Java project build path. You can add using Maven or download a jar file with transitive jars.
Let’s first add the latest Jackson Databind dependency in your maven project. I have used below dependency for this post which is the latest version:-
com.fasterxml.jackson.core jackson-databind 2.11.0
Note:- When we add jackosn-databind dependency then it will automatically download transitive dependencies of the 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 the 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. ObjectMapper class is useful to create JSON object, JSON Array, converting a Java object to a JSON object and vice versa. In this post, we will use the ObjectMapper class to convert a Java Object to a JSON object.
Target JSON Object to be created:-
{ "firstName" : "Amod", "lastName" : "Mahajan", "gender" : "M", "age" : 29, "salary" : 10987.77, "married" : false }
POJO Class
Let’s create a class with field name exactly (case sensitive) the same as node names in above JSON payload because with default setting while parsing Java Object to JSON object, it will look on getter setter methods of field names. In fact, access specifiers do not matter here. We will cover some interesting facts on it later.
package PojoPayloads; import java.io.File; import java.io.IOException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; class MSE_EmployeePojo { private String firstName; private String lastName; private String gender; private int age; private double salary; private boolean married; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public boolean getMarried() { return married; } public void setMarried(boolean married) { this.married = married; } }
POJO to JSON String
There are many ways or methods available in the ObjectMapper class. Below is a glimpse:-
You can write Java object as a string or byte array or into a file etc. For API we mostly used as a string or into a file. For proper formating use “writerWithDefaultPrettyPrinter()” before writing. Let’s create an object of MSE_EmployeePojo i.e. Java Object and write it as a JSON object.
public class UsageOfMSE_EmployeePojo { public static void main(String[] args) throws JsonProcessingException { MSE_EmployeePojo mse_EmployeePojo = new MSE_EmployeePojo(); mse_EmployeePojo.setFirstName("Amod"); mse_EmployeePojo.setLastName("Mahajan"); mse_EmployeePojo.setAge(29); mse_EmployeePojo.setSalary(10987.77); mse_EmployeePojo.setMarried(false); mse_EmployeePojo.setGender("M"); ObjectMapper objectMapper = new ObjectMapper(); String convertedJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(mse_EmployeePojo); System.out.println(convertedJson); } }
Output:-
{ "firstName" : "Amod", "lastName" : "Mahajan", "gender" : "M", "age" : 29, "salary" : 10987.77, "married" : false }
POJO to a JSON File
We just need to pass the target JSON file path and use the overloaded writeValue(File file, Object obj) method.
public class UsageOfMSE_EmployeePojo { public static void main(String[] args) throws IOException { MSE_EmployeePojo mse_EmployeePojo = new MSE_EmployeePojo(); mse_EmployeePojo.setFirstName("Amod"); mse_EmployeePojo.setLastName("Mahajan"); mse_EmployeePojo.setAge(29); mse_EmployeePojo.setSalary(10987.77); mse_EmployeePojo.setMarried(false); mse_EmployeePojo.setGender("M"); ObjectMapper objectMapper = new ObjectMapper(); String userDir = System.getProperty("user.dir"); File outputJsonFile = new File(userDir+ "\\src\\test\\resources\\EmployeePayload.json"); objectMapper.writerWithDefaultPrettyPrinter().writeValue(outputJsonFile, mse_EmployeePojo); } }
Refresh project folder if not auto refreshed (In case of Eclipse IDE). Navigate to the path you have provided.
You can see JSON details as below:-
Complete Code
package PojoPayloads; import java.io.File; import java.io.IOException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; class MSE_EmployeePojo { private String firstName; private String lastName; private String gender; private int age; private double salary; private boolean isMarried; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public boolean isMarried() { return isMarried; } public void setMarried(boolean isMarried) { this.isMarried = isMarried; } } public class UsageOfMSE_EmployeePojo { public static void main(String[] args) throws IOException { MSE_EmployeePojo mse_EmployeePojo = new MSE_EmployeePojo(); mse_EmployeePojo.setFirstName("Amod"); mse_EmployeePojo.setLastName("Mahajan"); mse_EmployeePojo.setAge(29); mse_EmployeePojo.setSalary(10987.77); mse_EmployeePojo.setMarried(false); mse_EmployeePojo.setGender("M"); ObjectMapper objectMapper = new ObjectMapper(); String convertedJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(mse_EmployeePojo); System.out.println(convertedJson); String userDir = System.getProperty("user.dir"); File outputJsonFile = new File(userDir+ "\\src\\test\\resources\\EmployeePayload.json"); objectMapper.writerWithDefaultPrettyPrinter().writeValue(outputJsonFile, mse_EmployeePojo); } }
You can download/clone the 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 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.
Thank you, it was simple to implement. Thanks for sharing the concept of POJO in detail which has helped to reach till this tutorial with understanding