Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is POJO?
3.
How to Create POJO Classes of a JSON Object Payload
4.
How to Create POJO Classes of a JSON Array Payload
5.
How to Create POJO Classes of a Nested JSON Payload
6.
Frequently Asked Questions
6.1.
What is POJO?
6.2.
Why is Serialization?
6.3.
Why is Deserialization?
6.4.
Can a Serialized object be transferred via a network?
6.5.
What is JSON Payload? 
7.
Conclusion
Last Updated: Mar 27, 2024
Medium

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

Author Akshat
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Do you know what POJO classes are? POJO stands for "Plain Old Java Object". It is a pure data structure with fields that may have getters and setters and the potential to override some object methods. But do you know how to create POJO classes of a JSON Payload? No worries, in this article, we will learn how to create POJO classes of a JSON object payload, JSON array payload, and nested JSON payload.

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

Fine! So let us first learn more about POJO and will go through the conversion of JSON payload to POJO classes.💫

What is POJO?

Plain Old Java Object (POJO) is a Java acronym. It is a common object that is not subject to any special limitations. There is no unique classpath necessary for the POJO file. It improves a Java program's ability to be read and reused.

Because of how simple they are to maintain, POJOs are now widely accepted. It is simple to read and write them. There is no naming scheme for properties and methods in a POJO class. It can be used by any Java program and is not dependent on any Java Framework.

A POJO class typically includes variables, along with their getters and setters.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

How to Create POJO Classes of a JSON Object Payload

The JSON in the example below is actually a 1:1 mapping, meaning that each key has a single value and a variety of value types.

{
  "badmintonBrand" : "Yonex",
  "racketName" : "Voltric 50 E-tune"
}

 

Let's begin creating POJO classes step by step.

We have the fields badmintonBrand and racketName in our JSON. Each field has values that match it. Now pay attention to value data types. There are String values for badmintonBrand and racketName. Let's map a field name to a data type as shown below: -

badmintonBrand - String

racketName - String

Now let's add some variables to the POJO class(POJOClassJSONObjectPayload) and set all variables as private to prevent direct manipulation.

package javaPackageName;
import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;

public class POJOClassJSONObjectPayload {
/*Data members*/
private String badmintonBrand;
private String racketName;

}

 

There should be a way to manipulate or retrieve these data because we created all variables as private. For each variable, let's add a getter and a setter method. A getter method retrieves a variable's value, whereas a setter method changes a variable's value externally.
 

public class POJOClassJSONObjectPayload {

/*Data members*/
private String badmintonBrand;
private String racketName;

/*Getters and Setters*/
public String getBadmintonBrand() {
return badmintonBrand;
}

public void setBadmintonBrand(String badmintonBrand){
this.badmintonBrand = badmintonBrand;
}

public String getRacketName() {
return racketName;
}

public void setRacketName(String racketName) {
this.racketName = racketName;
}
}

 

With the help of the aforementioned POJO class, an unlimited number of unique POJOClassJSONObjectPayload objects can be created, each of which can be converted into a JSON object and then parsed into POJO(of Class). If your API calls for a dynamic payload of class, you can easily make as many dynamic class payloads as you need with various data instead of hard-coding JSON objects. Simply POJO gives you the freedom to create and modify data in straightforward ways.

Using serialization and deserialization, we will convert a POJO into a JSON object and the other way around.

📌Serialization – Convert the class's objects of POJO to JSON or Object representation.

📌Deserialization – Convert a JSON object to an object of the class of POJO.

The code shown below demonstrates how to create a JSON object payload and then create a POJO class using this JSON object payload.

 

Code Implementation[POJOClassJSONObjectPayload.java]

package javaPackageName;

import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
public class POJOClassJSONObjectPayload {

/*Data members*/
private String badmintonBrand;
private String racketName;

/*Getters and Setters*/
public String getBadmintonBrand() {
return badmintonBrand;
}

public void setBadmintonBrand(String badmintonBrand){
this.badmintonBrand = badmintonBrand;
}

public String getRacketName() {
return racketName;
}

public void setRacketName(String racketName) {
this.racketName = racketName;
}

@Test
public void BadmintonJSONFromPOJOClass() throws JsonProcessingException {

/*Creating object of class*/
POJOClassJSONObjectPayload objpojo = new POJOClassJSONObjectPayload();

/*Set Values*/
objpojo.setBadmintonBrand("Yonex");
objpojo.setRacketName("Voltric 50 E-tune");

/*Class Object -> String(JSON Object PAYLOAD)*/
ObjectMapper objectMapper = new ObjectMapper();
String objpojoJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(objpojo);
System.out.println(objpojoJson);

/*String(JSON Object PAYLOAD) -> Class Object*/
POJOClassJSONObjectPayload objpojo2 = objectMapper.readValue(objpojoJson, POJOClassJSONObjectPayload.class);
System.out.println("Badminton Brand : "+objpojo2.getBadmintonBrand());
System.out.println("Racket Name : "+objpojo2.getRacketName());

}
}

 

Output-

output

How to Create POJO Classes of a JSON Array Payload

Below JSON Array is a collection of JSON Objects.

[ {
  "badmintonBrand" : "Yonex",
  "racketName" : "Voltric 50 E-Tune",
  "allPOJOClassJSONPayload" : null
}, {
  "badmintonBrand" : "Lining",
  "racketName" : "Woods N-90",
  "allPOJOClassJSONPayload" : null
}, {
  "badmintonBrand" : "Victor",
  "racketName" : "Ryuga",
  "allPOJOClassJSONPayload" : null
} ]

 

Let us create a POJO class(POJOClassJSONArrayPayload).

package javaPackageName;
public class POJOClassJSONArrayPayload {

/*Data members*/
private String badmintonBrand;
private String racketName;

/*Getters and Setters*/
public String getBadmintonBrand() {
return badmintonBrand;
}

public void setBadmintonBrand(String badmintonBrand){
this.badmintonBrand = badmintonBrand;
}

public String getRacketName() {
return racketName;
}

public void setRacketName(String racketName) {
this.racketName = racketName;
}
}


The code shown below demonstrates how to create a JSON array payload and then create a POJO class using this JSON array payload.

 

Code Implementation[POJOClassJSONObjectPayload.java]

package javaPackageName;
import java.util.List;
import java.util.ArrayList;
import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;
public class POJOClassJSONArrayPayload {

/*Data members*/
private String badmintonBrand;
private String racketName;

/*Getters and Setters*/
public String getBadmintonBrand() {
return badmintonBrand;
}

public void setBadmintonBrand(String badmintonBrand){
this.badmintonBrand = badmintonBrand;
}

public String getRacketName() {
return racketName;
}

public void setRacketName(String racketName) {
this.racketName = racketName;
}

public String allPOJOClassJSONPayload;

@Test
public void CreateList() throws JsonProcessingException {

/* Badminton Detail - 1*/
POJOClassJSONArrayPayload yonex = new POJOClassJSONArrayPayload();
yonex.setBadmintonBrand("Yonex");
yonex.setRacketName("Voltric 50 E-Tune");

/* Badminton Detail - 2*/
POJOClassJSONArrayPayload lining = new POJOClassJSONArrayPayload();
lining.setBadmintonBrand("Lining");
lining.setRacketName("Woods N-90");

/* Badminton Detail - 3*/
POJOClassJSONArrayPayload victor = new POJOClassJSONArrayPayload();
victor.setBadmintonBrand("Victor");
victor.setRacketName("Ryuga");

/* Creating List*/
List<POJOClassJSONArrayPayload> allBadmintonDetails = new ArrayList<POJOClassJSONArrayPayload>();
allBadmintonDetails.add(yonex);
allBadmintonDetails.add(lining);
allBadmintonDetails.add(victor);

/*Class Object -> String(JSON Array PAYLOAD)*/
ObjectMapper objMap3r = new ObjectMapper();
allPOJOClassJSONPayload = objMap3r.writerWithDefaultPrettyPrinter().writeValueAsString(allBadmintonDetails);
System.out.println(allPOJOClassJSONPayload);

/*String(JSON Array PAYLOAD) -> Class Object*/
ObjectMapper objMap3r2 = new ObjectMapper();
List<POJOClassJSONArrayPayload> allBaddyDetails = objMap3r2.readValue(allPOJOClassJSONPayload,
new TypeReference<List<POJOClassJSONArrayPayload>>() {
});

for (POJOClassJSONArrayPayload bad : allBaddyDetails) {
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
System.out.println("Badminton Brand : " + bad.getBadmintonBrand());
System.out.println("Racket Name : " + bad.getRacketName());

}
}
}

 

Output-

output

How to Create POJO Classes of a Nested JSON Payload

Below is an example of nested JSON.

{
  "governingBody" : "BWF",
  "hostingCity" : "Tokyo",
  "sponsors" : "TotalEnergies",
  "elitePlayers" : {
    "ms" : "LIN DAN",
    "ws" : "P V SINDHU"
  }
}


Let us create a POJO class.

Note - This section is similar to creating a POJO class of JSON object payload.

package javaPackageName;
public class POJOClassNestedJSONPayload {
public class ElitePlayers {

/*Data Members*/
private String mS;
private String wS;

/*Getter and Setter Methods*/
public String getMS() {
return mS;
}

public void setMS(String mS) {
this.mS = mS;
}

public String getWS() {
return wS;
}

public void setWS(String wS) {
this.wS = wS;
}
}


/*Data Members*/
private String governingBody;
private String hostingCity;
private String sponsors;
ElitePlayers elitePlayers;

/*Getter and Setter Methods*/
public String getGoverningBody() {
return governingBody;
}

public void setGoverningBody(String governingBody) {
this.governingBody = governingBody;
}

public String getHostingCity() {
return hostingCity;
}

public void setHostingCity(String hostingCity) {
this.hostingCity = hostingCity;
}

public String getSponsors() {
return sponsors;
}

public void setSponsors(String sponsors) {
this.sponsors = sponsors;
}

public ElitePlayers getElitePlayers() {
return elitePlayers;
}

public void setElitePlayers(ElitePlayers elitePlayers) {
this.elitePlayers = elitePlayers;
}
}

 

The code shown below demonstrates how to create a nested JSON payload and then create a POJO class using this nested JSON payload.

 

Code Implementation[POJOClassNestedJSONPayload.java]

package javaPackageName;
import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
public class POJOClassNestedJSONPayload {
public class ElitePlayers {

/*Data Members*/
private String mS;
private String wS;

/*Getter and Setter Methods*/
public String getMS() {
return mS;
}

public void setMS(String mS) {
this.mS = mS;
}

public String getWS() {
return wS;
}

public void setWS(String wS) {
this.wS = wS;
}
}


/*Data Members*/
private String governingBody;
private String hostingCity;
private String sponsors;
ElitePlayers elitePlayers;


/*Getter and Setter Methods*/
public String getGoverningBody() {
return governingBody;
}

public void setGoverningBody(String governingBody) {
this.governingBody = governingBody;
}

public String getHostingCity() {
return hostingCity;
}

public void setHostingCity(String hostingCity) {
this.hostingCity = hostingCity;
}

public String getSponsors() {
return sponsors;
}

public void setSponsors(String sponsors) {
this.sponsors = sponsors;
}

public ElitePlayers getElitePlayers() {
return elitePlayers;
}

public void setElitePlayers(ElitePlayers elitePlayers) {
this.elitePlayers = elitePlayers;
}

public class CreateNestedJSONFromPOJOClasses {

@Test

public void function() throws JsonProcessingException {
POJOClassNestedJSONPayload nestedPOJO = new POJOClassNestedJSONPayload();
nestedPOJO.setGoverningBody("BWF");
nestedPOJO.setHostingCity("Tokyo");
nestedPOJO.setSponsors("TotalEnergies");
ElitePlayers elitePlayers = new ElitePlayers();
elitePlayers.setMS("LIN DAN");
elitePlayers.setWS("P V SINDHU");
nestedPOJO.setElitePlayers(elitePlayers);

/*Class Object -> String(Nested JSON PAYLOAD)*/
ObjectMapper objMap3r = new ObjectMapper();
String nestedJsonPayload = objMap3r.writerWithDefaultPrettyPrinter().writeValueAsString(nestedPOJO);
System.out.println(nestedJsonPayload);

/*String(Nested JSON PAYLOAD) -> Class Object*/
POJOClassNestedJSONPayload objpojo2 = objMap3r.readValue(nestedJsonPayload, POJOClassNestedJSONPayload.class);
System.out.println("Elite Player[WS] : "+objpojo2.getElitePlayers().getWS());

}
}
}

 

Output-

output

We hope you have understood how to create JSON Payload POJO classes. 🙌

Must Read Array of Objects in Java

Frequently Asked Questions

What is POJO?

POJO stands for "Plain Old Java Object". It is a pure data structure with fields that may have getters and setters and the potential to override some Object methods.

Why is Serialization?

It is the process of converting a POJO object to a JSON object.

Why is Deserialization?

It is the process of converting a JSON object to a POJO object.

Can a Serialized object be transferred via a network?

Yes, a Serialized object can be transferred via a network.

What is JSON Payload? 

When you send or receive a data block from a server in response to an API request, it contains the payload.

Conclusion

This blog gave us an overview of how to create POJO classes of a JSON Payload. You can refer to similar articles for more information

  1. REST Assured – Creating JSON Object and array Request Body
  2. REST Assured –  Setting Default and Querying RequestSpecification
  3. REST Assured – Multiple Ways of Calling HTTP Methods on a RequestSpecification
  4. De-Serialization – JSON Object To Java Object Using Jackson API and Gson API in Rest-Assured.
  5. REST Assured – How to create POJO classes of a JSON Payload

 

You can refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.

Happy learning, Ninja!🥷

Previous article
REST Assured – How To Create a JSON Object and array Using Jackson API – ObjectMapper(createObjectNode())
Next article
Serialization – Java Object To JSON Object Using Jackson API and Gson API in Rest-Assured
Live masterclass