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.
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.
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