REST Assured Tutorial 29 – How to create POJO classes of a JSON Object Payload

As a part of End to End REST Assured Tutorial , in this post We will learn to create a simple POJO class for a simple JSON Object payload.

POJO classes are extensively used for creating JSON and XML payloads for API. Although there are many online platform to generate POJO and Java libraries to generate POJO classes automatically but still knowing to create POJO helps. Even you can use plain POJO concepts or POJO with builder pattern for data storage as well which we have seen in last post where I have stored employee data.

Although there is no restrictions on the way of creating POJO but creating with some guidelines help which we will see in this post.

Very simple JSON example

Below is a JSON with some nodes which is actually a 1:1 mapping i.e. each key has single value and type of values are mixed.

{
  "firstName": "Amod",
  "lastName": "Mahajan",
  "gender": "Male",
  "age": 28,
  "salary": 10000.56,
  "married": false
}

Let’s start creating POJO step by step.

Identify fields or variables for POJO class

Observe in example JSON, we have fields firstName, lastName , gender, age , salary and married. Each field has a corresponding values. Now focus on data types of values. firstName and lastName has String values while age has integer value, salary has double value and married has boolean. Let’s map data type with field name as below :-

firstName - String
lastName - Sring
age - int
gender - String
salary - double
married - boolean

Let’s create variables in POJO class now. Since it is storing a employee detail, name POJO class as Employee and make all variables (at least for this example and it is beginning ) as private so that no one can manipulate it directly.

package RestfulBookerPojo;

public class Employee {

	// private variables or data members of pojo class
	private String firstName;
	private String lastName;
	private String gender;
	private int age;
	private double salary;
	private boolean married; 
}

Add getter and setter methods for private variables

Since we have created all variables as private then there should be a way to manipulate or retrieve these data. Let’s add getter and setter methods for each variables. It is not mandatory to have getter and setter for all and depends upon need. But as of now let’s add getter and setter for all in same class. A getter method is to get value of a variable and a setter method is to set value of a variable from outside.

// 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 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;
	} 

If you are worrying that it is painful to create getter and setter methods manually for a large number of variables then do not worry. Every IDE gives you a shortcut to generate getter and setter methods. Just google it out.

Let’s do not add any constructors in class so that it will have a default constructors.

Complete POJO class

package RestfulBookerPojo;

public class Employee {

	// private variables or data members of pojo class
	private String firstName;
	private String lastName;
	private String gender;
	private int age;
	private double salary;
	private boolean married;
	
	// 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 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;
	} 
}

We are done now. We have created a POJO class of employee JSON. Now you must be thinking how this POJO class will help now?

Using above POJO class you can create any number of custom Employee objects and each object can be converted in to a JSON Object and Each JSON object can be parsed in to Employee POJO. If you have an API which requires dynamic payload of Employee then you can easily create as many as required employee payloads with different data in stead of creating hard coded JSON objects. In simple words POJO gives you flexibility of creating and manipulating data in simple ways.

We will create a JSON object form POJO and vice versa now which is generally called as serialization and deserialization using Jackson APIs. Do not worry about the terms serialization and deserialization as of now as I have not covered it yet. For time being, you just know :-

serialization – Convert Employee class object to JSON representation or Object

deserialization – reverse of serializing . Convert a JSON Object to Employee class object

package RestfulBookerPojo;

import org.testng.annotations.Test;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class EmployeeSerializationDeserialization {

	@Test
	public void createEmployeeJSONFromEmployeePOJOClass() throws JsonProcessingException
	{
		// Just create an object of Pojo class
		Employee employee = new Employee();
		// Set value as you wish
		employee.setFirstName("Amod");
		employee.setLastName("Mahajan");
		employee.setAge(29);
		employee.setGender("Male");
		employee.setSalary(3434343);
		employee.setMarried(false);
		
		// Converting a Java class object to a JSON payload as string
		ObjectMapper objectMapper = new ObjectMapper();
		String employeeJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee);
		System.out.println(employeeJson);
	}
	
	
	@Test
	public void getPojoFromEmployeeObject() throws JsonProcessingException
	{
		// Just create an object of Pojo class
		Employee employee = new Employee();
		// Set value as you wish
		employee.setFirstName("Amod");
		employee.setLastName("Mahajan");
		employee.setAge(29);
		employee.setGender("Male");
		employee.setSalary(3434343);
		employee.setMarried(false);
		
		// Converting a Java class object to a JSON payload as string
		ObjectMapper objectMapper = new ObjectMapper();
		String employeeJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee);
		
		
		// Converting EMployee json string to Employee class object
		Employee employee2 = objectMapper.readValue(employeeJson, 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("Gender of employee : "+employee2.getGender());
		System.out.println("Salary of employee : "+employee2.getSalary());
		System.out.println("Marital status of employee : "+employee2.getMarried());
	}
}

Output

{
  "firstName" : "Amod",
  "lastName" : "Mahajan",
  "gender" : "Male",
  "age" : 29,
  "salary" : 3434343.0,
  "married" : false
}
First Name of employee : Amod
Last Name of employee : Mahajan
Age of employee : 29
Gender of employee : Male
Salary of employee : 3434343.0
Marital status of employee : false

You can download/clone 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 post here, all API manual and automation related posts here and find frequently asked Java Programs here.

Many other topics you can navigate through menu.

10 thoughts on “REST Assured Tutorial 29 – How to create POJO classes of a JSON Object Payload

  1. Hi Amod,

    Will you be able to post a video where one dataprovider can pass multiple parameters to a test
    Basically, I have my payload ready and am able to read the data from excel. I also am able to read one attribute and pass its multiple data from excel to a test. But, I am not able to pass multiple attribute’s multiple data from excel to a test.

    Can one dataprovider returns only one attribute (used with Iterator)?

  2. Hi Amod,
    Can you please explain the steps for XML also. In json I learned how to set and get dynamic variable by reading your blogs. So I need to know how we will perform for XML file and how we will get the dynamic field or variables . What are the steps ?
    How we can proceed?

  3. Can we not pass a specific object from a pojo at runtime? example if i am three objects in pojo while initializing but during runtime i have a condition and i want to pass only 2 object from the pojo which has 3 objects. Can this be achieved?

  4. very nicely explained..I am new to this concept. Do u mind sharing the maven dependencies u hv used here ?

  5. Good one thanks for explaining this concept of seralization and deserialisation for json.

    and yes would like to know as Rahul Krishna has asked too, why we named it as POJO, its a class concept i.e. encapsulation and why we have named object with specific names like Amod

    why not generic names like employee because we might have 100 employees, so in that case will we create 100 objects with 100 unique names ?

  6. Amod ,if we have a objectmapper.createObjectNode() method which create a objectNode and we pass the same object to objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(), and in pojo we are skipping this step of creating objectNode ,rather directly passing our POJO to the objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(), then whats the difference or advantage of using POJO vs creating a objectNode and then passing it .In either way we are getting the JSON String .

  7. Hi Amod,

    Very elaborated and free flow explanation above. I would recommend you to provide library/dependency details in form of download link/maven/gradle. Like, here you have mentioned about usage of Jackson APIs. Even though if you have already mentioned corresponding link in some other post, but still it will help readers to have it handy. It is just my personal opinion.

    Regards,
    Lajish

Leave a Reply

Your email address will not be published. Required fields are marked *