In this tutorial, I will explain the creation of JSON Object Payload with the help of POJO (Plain Old Java Object).
What is POJO?
POJO stands for Plain Old Java Object. It is a very simple object, and it has no bounds or we can say that it has no restrictions other than the Java language specification. Also, it does not require any classpath.
A big advantage of POJO is it increases the readability and reusability of our project code and developers find it easy when understanding the code. Also, POJO is easy to write and anyone can understand them easily.
Now let’s deep dive into some technical terms about the POJO. Below are a few points about the POJO are:
A POJO should not have to extend prespecified classes.
Secondly, a POJO should not have implemented any prespecified interface.
Lastly, POJO should not contain prespecified annotations
A POJO class can follow some rules for better usability. These rules are:-
Each variable should be declared as private just to restrict direct access.
Each variable that needs to be accessed outside class may have a getter, a setter, or both methods. If the value of a field is stored after some calculations, then we must not have any setter method for that.
It Should have a default public constructor.
Can override toString(), hashcode, and equals() methods.
POJO classes are extensively used for creating JSON and XML payloads for API.
In the below example, let me create a simple JSON with some nodes which is actually a 1:1 mapping i.e. each key has a single value, and the type of values is mixed.
Let us create variables in the POJO class now for the above JSON. Now, a class name Employee will be created with the private data members as mentioned in the above JSON. Since we have created all variables as private, then there should be a way to manipulate or retrieve these data. So we create the corresponding getter and setter methods for these data members.
It is very tedious to create getter and setter methods for all the data members for big JSON strings. Every IDE gives you a shortcut to generate getter and setter methods. Here, I am using Eclipse and creating these getter and setter methods.
Select all the data members and Right-clickon the page. Then select Source and then select Generate Getter and Setter methods.
This opens a new screen as shown below.
You can select the data member for which you want to create the getter and setter method. I want to create the getter and setter methods for all the data members, so click on Select All and then click on the Generate Button. This will generate the getter and setter methods for all the data members.
Below is the sample code of the Employee table, which contains the data members needed for Employee JSON and their corresponding getter and setter methods.
public class Employee {
// private variables or data members of POJO class
private String firstName;
private String lastName;
private int age;
private double salary;
private String designation;
private String contactNumber;
private String emailId;
// Getter and setter methods
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 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 String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
}
Using the above POJO class, you can create any number of custom Employee objects and each object can be converted into a JSON Object and Each JSON object can be parsed into Employee POJO.
We will create a JSON object from POJO and vice versa now, which is generally called serialization and deserialization using Jackson APIs.
Serialization – Serialization is a process where you convert an Instance of a Class (Object of a class) into a Byte Stream. Here, we are converting Employee class object to JSON representation or Object
Deserialization – It is the reverse of serializing. In this process, we will read the Serialized byte stream from the file and convert it back into the Class instance representation. Here, we are converting a JSON Object to an Employee class object.
We are using Jackson API for Serialization and Deserialization. So, add the Jackson dependency to the project.
ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model (JsonNode), as well as related functionality for performing conversions. It is also highly customizable to work both with different styles of JSON content and to support more advanced object concepts such as polymorphism and object identity.
Now, let us create a Test Class to show Serialization.
public class EmployeeTest {
@Test
public void serializationTest() {
Employee employee = new Employee();
employee.setFirstName("Vibha");
employee.setLastName("Singh");
employee.setAge(30);
employee.setSalary(75000);
employee.setDesignation("Manager");
// Converting a Java class object to a JSON payload as string
ObjectMapper mapper = new ObjectMapper();
String employeeJson = mapper.writeValueAsString(employee);
String employeePrettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee);
System.out.println(employeeJson);
System.out.println(employeePrettyJson);
}
}try {
String employeeJson = mapper.writeValueAsString(employee);
System.out.println(employeeJson);
String employeePrettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee);
System.out.println(employeePrettyJson);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
The output of the above program is
Here, ObjectMapper from fasterxml.jackson.databind is used for Serialization.
writeValueAsString() is a method that can be used to serialize any Java value as a String.
writerWithDefaultPrettyPrinter() is used to pretty-print the JSON output. It is a Factory method for constructing ObjectWriter that will serialize objects using the default pretty printer for indentation.
I hope this has helped to clear your doubts regarding POJO and how to create JSON objects using POJO.
We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
This tutorial explains how to use JAXB (Java Architecture for XML Binding) to convert Java Objects to XML documents.
JAXB provides a fast and convenient way to marshal (write) Java Objects into XML and un-marshal (read) XML into Java Objects. It supports a binding framework that maps XML elements and attributes to Java fields and properties using Java annotations.
With Java releases lower than Java 11, JAXB was part of the JVM and you could use it directly without defining additional libraries.
As of Java 11, JAXB is not part of the JRE anymore, and you need to configure the relevant libraries via your dependency management system, for example, either Maven or Gradle.
Configure the Java compiler level to be at least 11 and add the JAXB dependencies to your pom file.
When we run the code above, we may check the console output to verify that we have successfully converted Java object to XML:
By default, the Marshaller uses UTF-8 encoding when generating XML data.
The javax.xml.bind.JAXBContext class provides a client’s entry point to JAXB API. By default, JAXB does not format the XML document. This saves space and prevents that any white-space may accidentally be interpreted as significant.
To have JAXB format the output, we simply set the Marshaller.JAXB_FORMATTED_OUTPUT property to true on the Marshaller. The marshal method uses an object and an output file where to store the generated XML as parameters.
You can see that we have used JAXB Annotations like @XMLRootElement are changed from Employee to EmployeeDetails.
@XMLElement has set the element name to GrossSalary from Salary.
The below example is the short way of writing the same test and saving XML. We need to add a constructor in the POJO class so that we can set the values to the variables through the Constructor.
import jakarta.xml.bind.annotation.*;
@XmlRootElement(name = "EmployeeDetails")
@XmlAccessorType(XmlAccessType.FIELD)
//Define the order in which the fields are written in XML
@XmlType(propOrder = { "firstName", "lastName", "gender", "age", "maritalStatus", "designation", "contactNumber",
"emailId", "salary" })
public class Employee {
private String firstName;
private String lastName;
private int age;
@XmlElement(name = "GrossSalary")
private double salary;
private String designation;
private String contactNumber;
private String emailId;
private String gender;
private String maritalStatus;
public Employee() {
super();
}
public Employee(String firstName, String lastName, int age, double salary, String designation, String contactNumber,
String emailId, String gender, String maritalStatus) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.salary = salary;
this.designation = designation;
this.contactNumber = contactNumber;
this.emailId = emailId;
this.gender = gender;
this.maritalStatus = maritalStatus;
}
// Getter and setter methods
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 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 String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getMaritalStatus() {
return maritalStatus;
}
public void setMaritalStatus(String maritalStatus) {
this.maritalStatus = maritalStatus;
}
@Override
public String toString() {
return "Employee [FirstName=" + firstName + ", LastName=" + lastName + ", Age=" + age + ", Salary=" + salary
+ ", Designation=" + designation + ", ContactNumber=" + contactNumber + ", EmailId=" + emailId
+ ", Gender=" + gender + ", MaritalStatus=" + maritalStatus + "]";
}
}
The below JAXB example for XML marshalling convert Java objects into an XML.
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Marshaller;
import jakarta.xml.bind.PropertyException;
import org.junit.Test;
import java.io.File;
import java.io.StringWriter;
public class SerializationDemo {
@Test
public void serializationTest2() {
try {
Employee employee = new Employee("Thomas", "Pawsey", 35, 100000, "Director", "+919999988822","Test@test.com", "married", "female");
// Create JAXB Context
JAXBContext context = JAXBContext.newInstance(Employee.class);
// Create Marshaller
Marshaller jaxbMarshaller = context.createMarshaller();
// Required formatting
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
// Write XML to StringWriter
StringWriter writer = new StringWriter();
jaxbMarshaller.marshal(employee, writer);
// Convert XML to String
String xmlContent = writer.toString();
System.out.println(xmlContent);
// Save the file
String userDir = System.getProperty("user.dir");
jaxbMarshaller.marshal(employee, new File(userDir + "\\src\\test\\resources\\JAXB_XML.xml"));
System.out.println("File is saved");
} catch (PropertyException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
When we run the code above, we may check the console output to verify that we have successfully converted Java object to XML:
The XML is saved under src/test/resources. To see this file, after the execution of the test, you need to refresh the project.
Similarly, we can unmarshal an XML to Java Objects in the next tutorial.
We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
The previous tutorials have explained the conversion of Java Objects to JSON payload and vice versa, i.e. conversion of JSON payload to Java Objects using Jackson API.
This tutorial explains parsing the XML document to Java objects using Jackson API.
To parse the above XML, we will use the Jackson library. Use the latest Jackson Library.
We will create an XML from POJO and vice versa now, which is generally called serialization and deserialization using Jackson APIs.
XmlMapper is a subclass of ObjectMapperwhich is used in JSON serialization. However, it adds some XML-specific tweaks to the parent class.
XmlMapper xmlMapper = new XmlMapper();
We can now look at how to use it to do the actual serialization. Let’s create a Java class first:
Below is the sample code of the Employee table, which contains the data members needed for Employee XML and their corresponding getter and setter methods.
public class Employee {
// Data members of POJO class
private String firstName;
private String lastName;
private int age;
private double salary;
private String designation;
private String contactNumber;
private String emailId;
private String gender;
private String maritalStatus;
// Getter and setter methods
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 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 String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getMaritalStatus() {
return maritalStatus;
}
public void setMaritalStatus(String maritalStatus) {
this.maritalStatus = maritalStatus;
}
}
Here, I have added JUnit4 dependency for the @Test annotation.
Writing XML is done using the various writeValue() methods that Jackson exposes.
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.junit.Test;
public class EmployeeXMLTest {
@Test
public void serializationTest() {
// Create an object of POJO class
Employee employee = new Employee();
employee.setFirstName("Vibha");
employee.setLastName("Singh");
employee.setAge(35);
employee.setSalary(135000);
employee.setDesignation("Manager");
employee.setContactNumber("+919999988822");
employee.setEmailId("abc@test.com");
employee.setMaritalStatus("married");
employee.setGender("female");
// Converting a Java class object to XML
XmlMapper xmlMapper = new XmlMapper();
try {
String employeeXml = xmlMapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee);
System.out.println(employeeXml);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}
Here, In this new structure, we have introduced a nested nameelement as well as contactdetails element which is further nested to emergencyDetailselements. With our current code, we cannot extract or create the new nested section. So, along with creating a POJO class for Employees, will create a POJO class for name, contactDetails, and emergencyDetails.
Employees
public class Employees {
Name name;
ContactDetails contactdetails;
private int age;
private double salary;
private String designation;
private String emailId;
private String gender;
private String maritalStatus;
// Getter and setter methods
public Name getName() {
return name;
}
public void setName(Name name) {
this.name = name;
}
public ContactDetails getContactdetails() {
return contactdetails;
}
public void setContactdetails(ContactDetails contactdetails) {
this.contactdetails = contactdetails;
}
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 String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getMaritalStatus() {
return maritalStatus;
}
public void setMaritalStatus(String maritalStatus) {
this.maritalStatus = maritalStatus;
}
}
Name
public class Name {
private String firtsname;
private String middlename;
private String lastname;
public String getFirtsname() {
return firtsname;
}
public void setFirtsname(String firtsname) {
this.firtsname = firtsname;
}
public String getMiddlename() {
return middlename;
}
public void setMiddlename(String middlename) {
this.middlename = middlename;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
ContactDetails-As you can see that EmergencyDetails element which contains emergency_no1, emergency_no2, and emergency_no3 are nested within ContactDetails, so we have created a separate POJO class for EmergencyDetails.
public class ContactDetails {
private String deskNumber;
private String mobileNumber;
EmergencyDetails emergencyDetails;
public EmergencyDetails getEmergencyDetails() {
return emergencyDetails;
}
public void setEmergencyDetails(EmergencyDetails emergencyDetails) {
this.emergencyDetails = emergencyDetails;
}
public String getDeskNumber() {
return deskNumber;
}
public void setDeskNumber(String deskNumber) {
this.deskNumber = deskNumber;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
}
EmergencyDetails
public class EmergencyDetails {
private String emergency_no1;
private String emergency_no2;
private String emergency_no3;
public String getEmergency_no1() {
return emergency_no1;
}
public void setEmergency_no1(String emergency_no1) {
this.emergency_no1 = emergency_no1;
}
public String getEmergency_no2() {
return emergency_no2;
}
public void setEmergency_no2(String emergency_no2) {
this.emergency_no2 = emergency_no2;
}
public String getEmergency_no3() {
return emergency_no3;
}
public void setEmergency_no3(String emergency_no3) {
this.emergency_no3 = emergency_no3;
}
}
Next, we create our serializeToXML() method:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.exc.StreamWriteException;
import com.fasterxml.jackson.databind.DatabindException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
public class ComplexEmployeeXMLTest {
@Test
public void serializationXML() {
Employees employee = new Employees();
Name empname = new Name();
empname.setFirtsname("John");
empname.setMiddlename("Dave");
empname.setLastname("William");
employee.setName(empname);
employee.setAge(35);
employee.setSalary(1355000);
employee.setDesignation("Manager");
ContactDetails contdetails = new ContactDetails();
contdetails.setDeskNumber("00-428507");
contdetails.setMobileNumber("+917823561231");
EmergencyDetails emergency = new EmergencyDetails();
emergency.setEmergency_no1("+91 1212898920");
emergency.setEmergency_no2("+91 9997722123");
emergency.setEmergency_no3("+91 8023881245");
contdetails.setEmergencyDetails(emergency);
employee.setContactdetails(contdetails);
employee.setEmailId("abc@test.com");
employee.setMaritalStatus("married");
employee.setGender("female");
XmlMapper xmlMapper = new XmlMapper();
try {
String employeeXml = xmlMapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee);
System.out.println(employeeXml);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
//To save the XML in a file and place under the project
String userDir = System.getProperty("user.dir");
try {
xmlMapper.writerWithDefaultPrettyPrinter()
.writeValue(new File(userDir + "\\src\\test\\resources\\NestedXMLExample.xml"), employee);
} catch (StreamWriteException e) {
e.printStackTrace();
} catch (DatabindException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The output of the above program is
The file is saved under src/test/resources as NestedXMLExample.
Open the xml file and it contains the XML Request Body.
There is another way to do the same job of converting Java Object to a complex XML, but which looks more sophisticated and less a number of lines of code.
I’ll use the same complex XML structure.
In this method, we will create a default constructor as well as a parametrized Constructor to pass the arguments for each POJO Class.
Employees
public class Employees {
Name name;
ContactDetails contactdetails;
private int age;
private double salary;
private String designation;
private String emailId;
private String gender;
private String maritalStatus;
public Employees() {
super();
}
public Employees(Name name, ContactDetails contactdetails, int age, double salary, String designation,
String emailId, String gender, String maritalStatus) {
this.name = name;
this.contactdetails = contactdetails;
this.age = age;
this.salary = salary;
this.designation = designation;
this.emailId = emailId;
this.gender = gender;
this.maritalStatus = maritalStatus;
}
// Getter and setter methods
public Name getName() {
return name;
}
public void setName(Name name) {
this.name = name;
}
public ContactDetails getContactdetails() {
return contactdetails;
}
public void setContactdetails(ContactDetails contactdetails) {
this.contactdetails = contactdetails;
}
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 String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getMaritalStatus() {
return maritalStatus;
}
public void setMaritalStatus(String maritalStatus) {
this.maritalStatus = maritalStatus;
}
}
Name
public class Name {
private String firtsname;
private String middlename;
private String lastname;
public Name() {
super();
}
public Name(String firtsname, String middlename, String lastname) {
super();
this.firtsname = firtsname;
this.middlename = middlename;
this.lastname = lastname;
}
public String getFirtsname() {
return firtsname;
}
public void setFirtsname(String firtsname) {
this.firtsname = firtsname;
}
public String getMiddlename() {
return middlename;
}
public void setMiddlename(String middlename) {
this.middlename = middlename;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
ContactDetails
public class ContactDetails {
private String deskNumber;
private String mobileNumber;
EmergencyDetails emergencyDetails;
public ContactDetails() {
super();
}
public ContactDetails(String deskNumber, String mobileNumber, EmergencyDetails emergencyDetails) {
super();
this.deskNumber = deskNumber;
this.mobileNumber = mobileNumber;
this.emergencyDetails = emergencyDetails;
}
public EmergencyDetails getEmergencyDetails() {
return emergencyDetails;
}
public void setEmergencyDetails(EmergencyDetails emergencyDetails) {
this.emergencyDetails = emergencyDetails;
}
public String getDeskNumber() {
return deskNumber;
}
public void setDeskNumber(String deskNumber) {
this.deskNumber = deskNumber;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
}
EmergencyDetails
public class EmergencyDetails {
private String emergency_no1;
private String emergency_no2;
private String emergency_no3;
public EmergencyDetails() {
super();
}
public EmergencyDetails(String emergency_no1, String emergency_no2, String emergency_no3) {
super();
this.emergency_no1 = emergency_no1;
this.emergency_no2 = emergency_no2;
this.emergency_no3 = emergency_no3;
}
public String getEmergency_no1() {
return emergency_no1;
}
public void setEmergency_no1(String emergency_no1) {
this.emergency_no1 = emergency_no1;
}
public String getEmergency_no2() {
return emergency_no2;
}
public void setEmergency_no2(String emergency_no2) {
this.emergency_no2 = emergency_no2;
}
public String getEmergency_no3() {
return emergency_no3;
}
public void setEmergency_no3(String emergency_no3) {
this.emergency_no3 = emergency_no3;
}
}
Now, let us create a Serialization Test.
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.junit.Test;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class XmlSerializationDemo2 {
@Test
public void serializationTest() {
try {
EmergencyDetails emergency = new EmergencyDetails("+91 894132345", "+91 8888221102", "+91 7223156288");
ContactDetails contdetails = new ContactDetails("00-428507", "+917823561231", emergency);
Name empname = new Name("Trina", "Sophia", "William");
// Converting a Java class object to a XML
XmlMapper xmlMapper = new XmlMapper();
String xmlString = xmlMapper.writerWithDefaultPrettyPrinter().writeValueAsString(new Employees(empname,
contdetails, 35, 1450000.00, "Director", "trina@test.com", "female", "married"));
System.out.println(xmlString);
// write XML string to file
String userDir = System.getProperty("user.dir");
File xmlOutput = new File(userDir + "\\src\\test\\resources\\XMLExample.xml");
FileWriter fileWriter = new FileWriter(xmlOutput);
fileWriter.write(xmlString);
fileWriter.close();
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The output of the above program is
The newly created XML file is saved under src/test/resources as shown in the below image.
Open the xml file and it contains the XML Request Body.
We have successfully serialized our Java object into XML and written it into an XML file.
In our serializationTest() function, we create an XmlMapper object, which is a child class to the ObjectMapper class used in JSON serialization. This class converts our Java Object into an XML output that we can now write to a file.
As we know, we can use toJson() to convert the JAVA objects to JSON Payload.
In the below example, I have created a POJO class with the name of EmployeeDetails. This class contains the data members corresponding to the JSON nodes and their corresponding getter and setter methods.
public class EmployeeDetails {
// private variables or data members of pojo class
private String name;
private double salary;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Below, will create a JSON payload and pass it as a request body to the Rest API.
@Test
public void createEmployee() throws IOException {
// Just create an object of Pojo class
EmployeeDetails emp = new EmployeeDetails();
emp.setName("GsonTest");
emp.setSalary(50000);
emp.setAge(25);
// Converting a Java class object to a JSON payload as string using Gson
Gson builder = new GsonBuilder().setPrettyPrinting().create();
String employeePrettyJsonPayload = builder.toJson(emp);
System.out.println("Request");
System.out.println(employeePrettyJsonPayload);
System.out.println("=========================================");
System.out.println("Response");
// GIVEN
given()
.baseUri("http://dummy.restapiexample.com/api")
.contentType(ContentType.JSON).body(emp)
// WHEN
.when()
.post("/v1/create")
// THEN
.then()
.assertThat().statusCode(200)
.body("status", equalTo("success"))
.body("data.name", equalTo("GsonTest"))
.body("data.salary", equalTo(50000))
.body("data.age", equalTo(25))
.body("message", equalTo("Successfully! Record has been added."))
.log().body();
}
}
Output
We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
This tutorial shows how to convert a Java map to JSON string using Jackson’s data binding. In the previous tutorials, I explained converting Java Objects/Arrays to JSON String using Jackson API. You can refer to the below tutorials.
This tutorial will show how to ignore certain fields when serializing an object to JSON or deserializing the JSON to object using Jackson 2.x.
This is very useful when the Jackson defaults aren’t enough and we need to control exactly what gets serialized to JSON – and there are several ways to ignore properties. One of the most common way is the use of @JsonIgnoreAnnotation, but it has some limitations. One of the major limitation is that if it is applied to getter method only, it will ignore setter method too. So, we cannot control if we want a property to be ignored for either Serialization or Deserialization.
Moreover, when there is a requirement to ignore multiple properties, it is tedious to mention @JsonIgnoreto all the properties which need to be ignored. Imagine there are 100 properties and we need to ignore 30 properties, it is tedious to mention @JsonIgnoreto each properties.
To start of, add Jackson databind dependency to the project. Always add the latest dependency to your project.
We need to create POJO for above JSON. So, let us create a class called Employee. Then create the private data members corresponding to the the nodes of the JSON and the getter and setter methods of these data members.
POJO Class
@JsonIgnoreProperties({"emailId","gender","maritalStatus"})
public class Employee {
// private variables or data members of pojo class
private String firstName;
private String lastName;
private int age;
private double salary;
private String designation;
private String contactNumber;
private String emailId;
private String gender;
private String maritalStatus;
// Getter and setter methods
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 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 String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getMaritalStatus() {
return maritalStatus;
}
public void setMaritalStatus(String maritalStatus) {
this.maritalStatus = maritalStatus;
}
}
Here, we have added emailId, gender and maritalStatus to @JsonIgnoreProperties as shown above.
Let us create a test where we pass values to all the nodes present in the JSON and see what happens to properties – emailId, gender and maritalStatus which are tagged as @JsonIgnoreProperties.
SerializationTest
@Test
public void serializationTest() {
// Create an object of POJO class
Employee employee = new Employee();
employee.setFirstName("Vibha");
employee.setLastName("Singh");
employee.setAge(30);
employee.setSalary(75000);
employee.setDesignation("Manager");
employee.setContactNumber("+919999988822");
employee.setEmailId("abc@test.com");
employee.setMaritalStatus("married");
employee.setGender("female");
// Converting a Java class object to a JSON payload as string
ObjectMapper mapper = new ObjectMapper();
try {
String employeeJson = mapper.writeValueAsString(employee);
System.out.println(employeeJson);
String employeePrettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee);
System.out.println(employeePrettyJson);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
Output
You can see that emailId, gender and maritalStatus are not present in JSON Payload.
Let us see the impact of @JsonIgnoreProperties to the setter or deserialized properties.
Deserialization Test
@Test
public void deserializationTest() {
String employeeString = "{\r\n"
+ " \"firstName\" : \"Deserialization\",\r\n"
+ " \"lastName\" : \"Test\",\r\n"
+ " \"age\" : 30,\r\n"
+ " \"salary\" : 75000.0,\r\n"
+ " \"designation\" : \"Manager\",\r\n"
+ " \"contactNumber\" : \"+919999988822\",\r\n"
+ " \"emailId\" : \"abc@test.com\",\r\n"
+ " \"gender\" : \"female\",\r\n"
+ " \"maritalStatus\" : \"married\"\r\n"
+ " }";
// Converting a JSON Payload to a JAVA Object
ObjectMapper mapper = new ObjectMapper();
Employee employee2 = null;
try {
employee2 = mapper.readValue(employeeString, Employee.class);
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (JsonProcessingException e) {
e.printStackTrace();
}
System.out.println("First Name of employee : " + employee2.getFirstName());
System.out.println("Last Name of employee : " + employee2.getLastName());
System.out.println("Age of employee : " + employee2.getAge());
System.out.println("Salary of employee : " + employee2.getSalary());
System.out.println("Designation of employee : " + employee2.getDesignation());
System.out.println("Contact Number of employee : " + employee2.getContactNumber());
System.out.println("EmailId of employee : " + employee2.getEmailId());
System.out.println("Marital Status of employee : " + employee2.getMaritalStatus());
System.out.println("Gender of employee : " + employee2.getGender());
}
Output
You can see that emailId, gender and maritalStatus – the values present in JSON for all of them are ignored and default values are retrieved.
POJO with allowGetters
allowGetters are enabled to allow “getters” to be used. This is commonly set to support defining “read-only” properties; ones for which there is a getter, but no matching setter: in this case, properties should be ignored for deserialization but NOT serialization. Another way to think about this setting is that setting it to `true` will “disable” ignoring of getters.
Default value is `false`, which means that getters with matching names will be ignored.
In the below example, I have defined emailId, gender and maritalStatus as allowGetters as True.
public class EmployeeTest {
@Test
public void serializationTest() {
Employee employee = new Employee();
employee.setFirstName("Vibha");
employee.setLastName("Singh");
employee.setAge(30);
employee.setSalary(75000);
employee.setDesignation("Manager");
employee.setContactNumber("+919999988822");
employee.setEmailId("abc@test.com");
employee.setMaritalStatus("married");
employee.setGender("female");
// Converting a Java class object to a JSON payload as string
ObjectMapper mapper = new ObjectMapper();
try {
String employeePrettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee);
System.out.println(employeePrettyJson);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
@Test
public void deserializationTest() {
String employeeString = "{\r\n"
+ " \"firstName\" : \"Deserialization\",\r\n"
+ " \"lastName\" : \"Test\",\r\n"
+ " \"age\" : 30,\r\n"
+ " \"salary\" : 75000.0,\r\n"
+ " \"designation\" : \"Manager\",\r\n"
+ " \"contactNumber\" : \"+919999988822\",\r\n"
+ " \"emailId\" : \"abc@test.com\",\r\n"
+ " \"gender\" : \"female\",\r\n"
+ " \"maritalStatus\" : \"married\"\r\n"
+ " }";
// Converting a JSON Payload to a JAVA Object
ObjectMapper mapper = new ObjectMapper();
Employee employee2 = null;
try {
employee2 = mapper.readValue(employeeString, Employee.class);
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (JsonProcessingException e) {
e.printStackTrace();
}
System.out.println("First Name of employee : " + employee2.getFirstName());
System.out.println("Last Name of employee : " + employee2.getLastName());
System.out.println("Age of employee : " + employee2.getAge());
System.out.println("Salary of employee : " + employee2.getSalary());
System.out.println("Designation of employee : " + employee2.getDesignation());
System.out.println("Contact Number of employee : " + employee2.getContactNumber());
System.out.println("EmailId of employee : " + employee2.getEmailId());
System.out.println("Marital Status of employee : " + employee2.getMaritalStatus());
System.out.println("Gender of employee : " + employee2.getGender());
}
}
Output
In the below image, it shows that values of emailId, gender and maritalStatus are ignored and default value is passed.
POJO with allowSetters
allowSetters – Property that can be enabled to allow “setters” to be used. This could be used to specify “write-only” properties; ones that should not be serialized out, but that may be provided in for deserialization. Another way to think about this setting is that setting it to `true` will “disable” ignoring of setters.
Default value is `false`, which means that setters with matching names will be ignored.
public class EmployeeTest {
@Test
public void serializationTest() {
Employee employee = new Employee();
employee.setFirstName("Vibha");
employee.setLastName("Singh");
employee.setAge(30);
employee.setSalary(75000);
employee.setDesignation("Manager");
employee.setContactNumber("+919999988822");
employee.setEmailId("abc@test.com");
employee.setMaritalStatus("married");
employee.setGender("female");
// Converting a Java class object to a JSON payload as string
ObjectMapper mapper = new ObjectMapper();
try {
String employeePrettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee);
System.out.println(employeePrettyJson);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
System.out.println("########################################");
}
@Test
public void deserializationTest() {
String employeeString = "{\r\n"
+ " \"firstName\" : \"Deserialization\",\r\n"
+ " \"lastName\" : \"Test\",\r\n"
+ " \"age\" : 30,\r\n"
+ " \"salary\" : 75000.0,\r\n"
+ " \"designation\" : \"Manager\",\r\n"
+ " \"contactNumber\" : \"+919999988822\",\r\n"
+ " \"emailId\" : \"abc@test.com\",\r\n"
+ " \"gender\" : \"female\",\r\n"
+ " \"maritalStatus\" : \"married\"\r\n"
+ " }";
// Converting a JSON Payload to a JAVA Object
ObjectMapper mapper = new ObjectMapper();
Employee employee2 = null;
try {
employee2 = mapper.readValue(employeeString, Employee.class);
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (JsonProcessingException e) {
e.printStackTrace();
}
System.out.println("First Name of employee : " + employee2.getFirstName());
System.out.println("Last Name of employee : " + employee2.getLastName());
System.out.println("Age of employee : " + employee2.getAge());
System.out.println("Salary of employee : " + employee2.getSalary());
System.out.println("Designation of employee : " + employee2.getDesignation());
System.out.println("Contact Number of employee : " + employee2.getContactNumber());
System.out.println("EmailId of employee : " + employee2.getEmailId());
System.out.println("Marital Status of employee : " + employee2.getMaritalStatus());
System.out.println("Gender of employee : " + employee2.getGender());
System.out.println("########################################");
}
}
Output
We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
This tutorial will show how to ignore certain fields when serializing an object to JSON using Jackson 2.x.
This is very useful when the Jackson defaults aren’t enough, and we need to control exactly what gets serialized to JSON – and there are several ways to ignore properties. One of the most common ways is the use of @JsonIgnore Annotation.
To start off, add Jackson’s databind dependency to the project. Always add the latest dependency to your project.
@JsonIgnore is used at field level to mark a property or list of properties to be ignored.
The Jackson’s @JsonIgnore annotation can be placed on fields, getters/setters and constructor parameters mark a property to be ignored during the serialization to JSON (or deserialization from JSON). If @JsonIgnore is the only annotation associated with a property, it will also cause the whole property to be ignored: that is, if setter has this annotation and getter has no annotations, the getter is also effectively ignored.
To learn about Serialization and Deserialization of a JSON Object using Jackson API, refer to this
To create a POJO of the above JSON, we need to create a class with the name Employee. Create private data members corresponding to these JSON nodes, and then create the corresponding getter and setter methods.
Here, I have assigned emailId and gender as @JsonIgnore.
public class Employee {
// private variables or data members of pojo class
private String firstName;
private String lastName;
private int age;
private double salary;
private String designation;
private String contactNumber;
@JsonIgnore
private String emailId;
@JsonIgnore
private String gender;
private String maritalStatus;
// Getter and setter methods
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 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 String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getMaritalStatus() {
return maritalStatus;
}
public void setMaritalStatus(String maritalStatus) {
this.maritalStatus = maritalStatus;
}
}
Now, let us create a SerializationTest with the above-mentioned POJO.
@Test
public void serializationTest() {
Employee employee = new Employee();
employee.setFirstName("Vibha");
employee.setLastName("Singh");
employee.setAge(30);
employee.setSalary(75000);
employee.setDesignation("Manager");
employee.setContactNumber("+919999988822");
employee.setEmailId("abc@test.com");
employee.setMaritalStatus("married");
employee.setGender("female");
// Converting a Java class object to a JSON payload as string
ObjectMapper mapper = new ObjectMapper();
try {
String employeePrettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee);
System.out.println(employeePrettyJson);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
System.out.println("########################################");
}
Output
As you can see here that emailId and gender nodes are not present in this JSON payload.
Now, let us see an example of deserialization where nodes that are assigned as @JsonIgnore return null values.
@Test
public void deserializationTest() throws JsonMappingException, JsonProcessingException {
String employeeString = "{\r\n"
+ " \"firstName\" : \"Deserialization\",\r\n"
+ " \"lastName\" : \"Test\",\r\n"
+ " \"age\" : 30,\r\n"
+ " \"salary\" : 75000.0,\r\n"
+ " \"designation\" : \"Manager\",\r\n"
+ " \"contactNumber\" : \"+919999988822\",\r\n"
+ " \"emailId\" : \"abc@test.com\",\r\n"
+ " \"gender\" : \"female\",\r\n"
+ " \"maritalStatus\" : \"married\"\r\n"
+ " }";
// Converting a Java class object to a JSON payload as string
ObjectMapper mapper = new ObjectMapper();
Employee employee2 = mapper.readValue(employeeString, Employee.class);
System.out.println("First Name of employee : " + employee2.getFirstName());
System.out.println("Last Name of employee : " + employee2.getLastName());
System.out.println("Age of employee : " + employee2.getAge());
System.out.println("Salary of employee : " + employee2.getSalary());
System.out.println("Designation of employee : " + employee2.getDesignation());
System.out.println("Contact Number of employee : " + employee2.getContactNumber());
System.out.println("EmailId of employee : " + employee2.getEmailId());
System.out.println("Marital Status of employee : " + employee2.getMaritalStatus());
System.out.println("Gender of employee : " + employee2.getGender());
}
Output
We have values for fields emailId and gender in JSON, but it has not been deserialized as you can see it has default values, not from JSON.
I hope this has helped you to understand @JsonIgnore. Cheers!! Have happy learning!!
This dependency will also transitively add the following libraries to the classpath:
jackson-annotations
jackson-core
In the below example, let us assume that we need to create a new Employee (POST Request). To start with, we need to create a POJO class of the JSON payload (EmployeeDetails). This POJO class should contain the data members corresponding to the JSON nodes and their corresponding getter and setter methods.
public class EmployeeDetails {
// private variables or data members of pojo class
private String name;
private double salary;
private int age;
// Getter and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Now that we have our POJO class, we can start writing some REST Assured Serialization tests!
Let’s start with REST Assured Serialization with JSON. I want to send a POST request to my EmployeeDetails API that will add a new Employee to the database. I will send a POJO of the employee in the request body. This is what the code looks like in the test class:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.restassured.http.ContentType;
import org.junit.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class EmployeeTests {
@Test
public void createEmployee() {
// Create an object of POJO class
EmployeeDetails emp = new EmployeeDetails();
emp.setName("Vibha");
emp.setSalary(75000);
emp.setAge(30);
// Converting a Java class object to a JSON payload as string
ObjectMapper mapper = new ObjectMapper();
String employeePrettyJson = null;
try {
employeePrettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
System.out.println("Request");
System.out.println(employeePrettyJson);
System.out.println("=========================================");
System.out.println("Response");
// GIVEN
given().baseUri("https://dummy.restapiexample.com/api").contentType(ContentType.JSON).body(emp)
// WHEN
.when().post("/v1/create")
// THEN
.then().assertThat().statusCode(200).body("data.name", equalTo("Vibha"))
.body("message", equalTo("Successfully! Record has been added.")).log().body();
}
}
The output of the above program is
If you want to see the structure of the Request, then add the below in the test code.
ObjectMapper mapper = new ObjectMapper();
String employeePrettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp);
System.out.println(employeePrettyJson);
REST Assured Serialization with Jackson handled all the serialization work for us. Great! See, this has become so simple with the help of Jackson API.
We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
In the previous tutorial, I explained thecreation of JSON Array using POJO. In this tutorial, I will explain the creation of a nested JSON Object (JSON with multiple nodes) using POJO.
It is recommended to go through these tutorials to understand POJO, JSON Object, and JSON Array.
We are using Jackson API for Serialization and Deserialization. So, add the Jackson dependency to the project. We need to add the below-mentioned dependencies to run this example.
It is very overwhelming to handle this type of nested JSON Object at a glance. So, we will split this into small parts or objects. So basically, we can split the above JSON into 4 parts – Employee, Contractors, CompanyPFDetails, and NestedPOJODemo.
companyName, companyEmailId, companyNumber, and companyAddress are 1:1 mapping in the payload. supportedSalaryBanks is an array of String values.
Employeehas value as an array of employees. There is no ready-made data type to represent elements of this array as a whole. So here we need to create a POJO class that can contain all details of an employee.
To represent an array of Employees and Contractors
Create a POJO class for CompanyPFDetails and add it to the main payload.
Now, let us see various POJO classes.
Employee POJO Class
public class Employee {
// private variables or data members of pojo class
private String firstName;
private String lastName;
private int age;
private double salary;
private String designation;
private String contactNumber;
private String emailId;
// Getter and setter methods
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 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 String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
}
Contractors POJO Class
public class Contractors {
// private variables or data members of pojo class
private String firstName;
private String lastName;
private String contractFrom;
private String contractTo;
private String contactNumber;
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 getContractFrom() {
return contractFrom;
}
public void setContractFrom(String contractFrom) {
this.contractFrom = contractFrom;
}
public String getContractTo() {
return contractTo;
}
public void setContractTo(String contractTo) {
this.contractTo = contractTo;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
}
CompanyPFDetails POJO Class
public class CompanyPFDetails {
private String pfName;
private int pfYear;
private int noOfEmployees;
public String getPfName() {
return pfName;
}
public void setPfName(String pfName) {
this.pfName = pfName;
}
public int getPfYear() {
return pfYear;
}
public void setPfYear(int pfYear) {
this.pfYear = pfYear;
}
public int getNoOfEmployees() {
return noOfEmployees;
}
public void setNoOfEmployees(int noOfEmployees) {
this.noOfEmployees = noOfEmployees;
}
}
NestedPOJODemo class
public class NestedPOJODemo {
// private variables or data members of pojo class
private String companyName;
private String companyEmailId;
private String companyNumber;
private String companyAddress;
private List<String> supportedSalaryBanks;
List<Employee> employee;
List<Contractors> contractors;
CompanyPFDetails companyPFDetails;
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getCompanyEmailId() {
return companyEmailId;
}
public void setCompanyEmailId(String companyEmailId) {
this.companyEmailId = companyEmailId;
}
public String getCompanyNumber() {
return companyNumber;
}
public void setCompanyNumber(String companyNumber) {
this.companyNumber = companyNumber;
}
public String getCompanyAddress() {
return companyAddress;
}
public void setCompanyAddress(String companyAddress) {
this.companyAddress = companyAddress;
}
public List<String> getSupportedSalaryBanks() {
return supportedSalaryBanks;
}
public void setSupportedSalaryBanks(List<String> supportedSalaryBanks) {
this.supportedSalaryBanks = supportedSalaryBanks;
}
public List<Employee> getEmployee() {
return employee;
}
public void setEmployee(List<Employee> employee) {
this.employee = employee;
}
public List<Contractors> getContractors() {
return contractors;
}
public void setContractors(List<Contractors> contractors) {
this.contractors = contractors;
}
public CompanyPFDetails getCompanyPFDetails() {
return companyPFDetails;
}
public void setCompanyPFDetails(CompanyPFDetails companyPFDetails) {
this.companyPFDetails = companyPFDetails;
}
}
Let’s create a JSON Payload using the above POJO classes.
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class NestedPOJOTest {
@Test
public void createNestedPOJO() throws IOException {
NestedPOJODemo demo = new NestedPOJODemo();
demo.setCompanyName("QAAutomation");
demo.setCompanyEmailId("qaautomation@org.com");
demo.setCompanyNumber("+353891234121");
demo.setCompanyAddress("12, HeneryStreet, Dublin, D12PW20");
List<String> supportedSalaryBanks = new ArrayList<String>();
supportedSalaryBanks.add("AIB");
supportedSalaryBanks.add("BOI");
supportedSalaryBanks.add("PSB");
demo.setSupportedSalaryBanks(supportedSalaryBanks);
// First Employee
Employee emp1 = new Employee();
emp1.setFirstName("Vibha");
emp1.setLastName("Singh");
emp1.setAge(30);
emp1.setSalary(75000);
emp1.setDesignation("Manager");
emp1.setContactNumber("+919999988822");
emp1.setEmailId("abc@test.com");
// Second Employee
Employee emp2 = new Employee();
emp2.setFirstName("Neha");
emp2.setLastName("Verms");
emp2.setAge(35);
emp2.setSalary(60000);
emp2.setDesignation("Lead");
emp2.setContactNumber("+914442266221");
emp2.setEmailId("xyz@test.com");
// Third Employee
Employee emp3 = new Employee();
emp3.setFirstName("Rajesh");
emp3.setLastName("Gupta");
emp3.setAge(20);
emp3.setSalary(40000);
emp3.setDesignation("Intern");
emp3.setContactNumber("+919933384422");
emp3.setEmailId("pqr@test.com");
// Creating a List of Employees
List<Employee> employeeList = new ArrayList<Employee>();
employeeList.add(emp1);
employeeList.add(emp2);
employeeList.add(emp3);
demo.setEmployee(employeeList);
// First Contractor
Contractors contractor1 = new Contractors();
contractor1.setFirstName("John");
contractor1.setLastName("Mathew");
contractor1.setContractFrom("Jan-2018");
contractor1.setContractTo("Aug-2022");
contractor1.setContactNumber("+919631384422");
// Second Contractor
Contractors contractor2 = new Contractors();
contractor2.setFirstName("Seema");
contractor2.setLastName("Mathew");
contractor2.setContractFrom("Jun-2019");
contractor2.setContractTo("Jun-2023");
contractor2.setContactNumber("+919688881422");
// Creating a List of Contractors
List<Contractors> contractorList = new ArrayList<Contractors>();
contractorList.add(contractor1);
contractorList.add(contractor2);
demo.setContractors(contractorList);
CompanyPFDetails pf = new CompanyPFDetails();
pf.setPfName("XYZ");
pf.setPfYear(2020);
pf.setNoOfEmployees(100);
demo.setCompanyPFDetails(pf);
ObjectMapper mapper = new ObjectMapper();
String nestedJsonPayload = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(demo);
System.out.println(nestedJsonPayload);
}
}
Here, I have used ObjectMapper for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model (JsonNode), as well as related functionality for performing conversions.
We can save this JSON payload in a file in the project or any location of your choice. Here, I’m saving this Nested JSON Payload in a file within src/test/resources.
We need to create an Employee class that contains private data members and the corresponding getter and setter methods of these data members.
Below is an Employee Class with private data members, as well as the corresponding getter and setter methods of these data members. Every IDE provides a shortcut to create these getter and setter methods.
public class Employee {
// private variables or data members of POJO class
private String firstName;
private String lastName;
private int age;
private double salary;
private String designation;
private String contactNumber;
private String emailId;
// Getter and setter methods
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 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 String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
}
Serialization – Serialization is a process where you convert an Instance of a Class (Object of a class) into a Byte Stream. Here, we are converting Employee class object to JSON Array representation or Object.
Deserialization – It is the reverse of serializing. In this process, we will read the Serialized byte stream from the file and convert it back into the Class instance representation. Here, we are converting a JSON Array to an Employee class object.
We are using Jackson API for Serialization and Deserialization. So, add the Jackson dependency to the project.