How to create Nested JSON Object using POJO – Jackson API

HOME

In the previous tutorial, I have explained the creation 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 about POJO, JSON Object and JSON Array.

How to create JSON Object Payload using POJO – Jackson API

How to create JSON Array Payload using POJO – Jackson API

We will use a nested JSON Object (a combination of JSON Arrays and objects).

{
  "companyName": "QAAutomation",
  "companyEmailId": "qaautomation@org.com",
  "companyNumber": "+353891234121", 
  "companyAddress": "12, HeneryStreet, Dublin, D12PW20", 
  "supportedSalaryBanks": [
    "AIB",
    "BOI",
    "PSB"
  ],
  "employee": [
    { 
	  "firstName" : "Vibha",
      "lastName" : "Singh",
      "age" : 30,
      "salary" : 75000.0,
      "designation" : "Manager",
      "contactNumber" : "+919999988822",
      "emailId" : "abc@test.com"
    },
    {
      "firstName" : "Neha",
      "lastName" : "Verma",
      "age" : 25,
      "salary" : 60000.0,
      "designation" : "Lead",
      "contactNumber" : "+914442266221",
      "emailId" : "xyz@test.com"
    },
    {
      "firstName" : "Rajesh",
      "lastName" : "Gupta",
      "age" : 20,
      "salary" : 40000.0,
      "designation" : "Intern",
      "contactNumber" : "+919933384422",
      "emailId" : "pqr@test.com"
    }
  ],
  "contractors": [
    {
      "firstName": "John",
      "lastName": "Mathew",
      "contractFrom": "Jan-2018",
      "contractTo": "Aug-2022",
	  "contactNumber" : "+919631384422"
    },
    {
      "firstName": "Seema",
      "lastName": "Prasad",
      "contractFrom": "Jun-2019",
      "contractTo": "Jun-2023"
	  "contactNumber" : "+919688881422"
    }
  ],
  "companyPFDeails": {
    "pfName": "XYZ",
    "pfYear": 2020,
    "noOfEmployees": 100
  }
}

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.

	private String companyName;
	private String companyEmailId;
	private String companyNumber;
	private String companyAddress;
	private List<String> supportedSalaryBanks;

Employee has 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

	List<Employee> employee;
	List<Contractors> 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.

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);

	}

}

We are using Jackson API for Serialization and Deserialization. So, add the Jackson dependency to the project.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.0</version>
</dependency>

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.

String userDir = System.getProperty("user.dir");
mapper.writerWithDefaultPrettyPrinter().writeValue(new File(userDir + "\\src\\test\\resources\\NestedEmployeePayload.json"), demo);
	}

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s