Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
About Jackson API
2.1.
Class ObjectMapper
3.
Converting Java Object To JSON Object Using Jackson API
3.1.
POJO Class
3.2.
POJO to JSON String
3.3.
POJO to the JSON File
4.
Converting Java Object To JSON Object Using Gson API
4.1.
About GSON
4.2.
POJO Class
4.3.
POJO to JSON String
5.
Frequently Asked Questions
5.1.
What is POJO?
5.2.
What is Serialization?
5.3.
What is Deserialization?
5.4.
Can a Serialized object be transferred via a network?
5.5.
What is JSON Payload? 
6.
Conclusion
Last Updated: Mar 27, 2024
Medium

Serialization – Java Object To JSON Object Using Jackson API and Gson API in Rest-Assured

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

Introduction

Do you know what serialization is? It is the process of converting a POJO object to the JSON object. But do you know how to convert the Java object to the JSON object using Jackson API and Gson API in Rest-Assured? 

Serialization – Java Object To JSON Object Using Jackson API and Gson API in Rest-Assured

Fine! So let us first learn more about Jackson API, and then we will go through the conversion of the Java object to the JSON object using Jackson API and Gson API.💫

About Jackson API

Jackson API is a fast JSON processor in Java. Jackson API allows us to do many things, including serialization, deserialization, reading, and writing JSON files.

We must include Jackson API in the Java project build path to use it. You can download a jar file with transitive jars or add it using Maven.

The most recent Jackson Databind dependency must first be added to your Maven project.

Class ObjectMapper

The Jackson API's most potent class. A Java object can be converted to JSON and vice versa using the ObjectMapper class

Target JSON Object to be created:-

{
  "firstName": "Akshat",
  "lastName": "Agarwal",
  "subject": "Data structures and algorithms",
  "school": "Coding Ninjas"
}
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

Converting Java Object To JSON Object Using Jackson API

This section will discuss converting the Java object to JSON using Jackson API below.

POJO Class

Because the default setting when parsing Java object to JSON object will look at getter and setter methods of field names, let's create a class with field names precisely the same as node names in the above JSON payload. Access specifiers are irrelevant in this case. 

package PojoPayloads;

import java.io.File;
import java.io.IOException;

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

class MSE_StudentPojo {

private String firstName;
private String lastName;
private String subject;
private String school;

/* 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 getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
}

POJO to JSON String

Java objects can be written as strings, byte arrays, files, etc. We typically use it as a string or as a file for API. Use "writerWithDefaultPrettyPrinter()" before writing to format the text properly. Let's create the Java object for MSE StudentPojo and then convert it to JSON.

public class UsageOfMSE_StudentPojo {

public static void main(String[] args) throws JsonProcessingException {

MSE_StudentPojo MSE_StudentPojo = new mse_StudentPojo();
mse_StudentPojo.setFirstName("Akshat");
mse_StudentPojo.setLastName("Agarwal");
mse_StudentPojo.setSubject("Data Structures and Algorithms");
mse_StudentPojo.setSchool("Coding Ninjas");


ObjectMapper objectMapper = new ObjectMapper();
String convertedJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(mse_StudentPojo);
System.out.println(convertedJson);
}


}

 

Output-

output

POJO to the JSON File

We only need to use the overloaded method writeValue(File file, Object obj) and pass the path to the target JSON file.

public class UsageOfMSE_StudentPojo {

public static void main(String[] args) throws IOException {

MSE_StudentPojo MSE_StudentPojo = new mse_StudentPojo();
mse_StudentPojo.setFirstName("Akshat");
mse_StudentPojo.setLastName("Agarwal");
mse_StudentPojo.setSubject("Data Structures and Algorithms");
mse_StudentPojo.setSchool("Coding Ninjas");

ObjectMapper objectMapper = new ObjectMapper();
String userDir = System.getProperty("user.dir");
File outputJsonFile = new File(userDir+ "\\src\\test\\resources\\StudentPayload.json");
objectMapper.writerWithDefaultPrettyPrinter().writeValue(outputJsonFile, mse_StudentPojo);
}


}

 

Complete Code-

package PojoPayloads;

import java.io.File;
import java.io.IOException;

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

class MSE_StudentPojo {

private String firstName;
private String lastName;
private String subject;
private String school;



/* 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 getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
}


public class UsageOfMSE_StudentPojo {

public static void main(String[] args) throws IOException {

MSE_StudentPojo MSE_StudentPojo = new mse_StudentPojo();
mse_StudentPojo.setFirstName("Akshat");
mse_StudentPojo.setLastName("Agarwal");
mse_StudentPojo.setSubject("Data Structures and Algorithms");
mse_StudentPojo.setSchool("Coding Ninjas");

ObjectMapper objectMapper = new ObjectMapper();
String convertedJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(mse_StudentPojo);
System.out.println(convertedJson);

String userDir = System.getProperty("user.dir");
File outputJsonFile = new File(userDir+ "\\src\\test\\resources\\StudentPayload.json");
objectMapper.writerWithDefaultPrettyPrinter().writeValue(outputJsonFile, mse_StudentPojo);
}

}

Converting Java Object To JSON Object Using Gson API

Here in this section, we will first learn what GSON is. Then we will see how we can convert the java object to the JSON object using GSON API.

About GSON

Gson is the Java library that can transform Java Objects into their JSON representation. Additionally, it can translate a JSON string into a corresponding Java object. Gson can operate on any Java object, even if you don't have the source code.

👉For converting Java objects to JSON and vice versa, provide toJson() and fromJson() methods.

👉Permit conversion of existing, immutable objects to and from JSON.

👉Java Generics are supported extensively.

👉Allow custom object representations.

👉Support objects of arbitrary complexity.

Gson is a class that the Gson library offers. It is the primary class for using Gson. To use Gson, you must create a Gson instance first, then call the toJson(Object) or fromJson(String, Class) methods. Because Gson instances are thread-safe, you can freely reuse them across various threads.

If the default settings are all you require, calling a new Gson() will allow you to create a Gson instance. Additionally, you can create a Gson instance with various configuration options using GsonBuilder, including pretty-printing, versioning support, a customized JsonSerializer, JsonDeserializer, and InstanceCreator.

Let’s learn about serialization using Gson now.

Target JSON Object-

{
  "firstName": "Akshat",
  "lastName": "Agarwal",
  "subject": "Data structures and algorithms",
  "school": "Coding Ninjas"
}

POJO Class

Because the default setting when parsing Java objects to JSON objects will look at getter setter methods of field names, let's create a class with a field name the same as node names in the above JSON payload. Access specifiers are irrelevant in this case. Later, we'll talk about some fascinating facts about it.

package SerializationDeserialization;

public class Student {

private String firstName;
private String lastName;
private String subject;
private String school;

/* 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 getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
}

POJO to JSON String

Let's see how to convert the Java Object to the JSON object and into a .json file.

The "toJson()" method provided by the Gson class has multiple overloads. Let’s see it below.

package SerializationDeserialization;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonIOException;

public class SerializeJavaToJsonObjectUsingGSON {

public static void main(String[] args) throws JsonIOException, IOException {

/* Create a Student java object */
Student studentObject = new Student();
studentObject.setFirstName("Akshat");
studentObject.setLastName("Agarwal");
studentObject.setSubject("Data Structures and Algorithms");
studentObject.setSchool("Coding Ninjas");



/* Create a Gson object */
Gson gson = new Gson();
/* toJson(Object src) method converts Java object to JSON object */
String studentJsonSring = gson.toJson(studentObject);
/*  Printing JSON string. It will be pretty print */
System.out.println("Non-pretty JSON String :- ");
System.out.println(studentJsonSring);

/* We can create a configurable Gson instance using GsonBuilder class*/
Gson gsonBuilder = new GsonBuilder().setPrettyPrinting().create();
String studentJsonSringUsingJsonBuilder = gsonBuilder.toJson(studentObject);
System.out.println("Pretty JSON String :- ");
System.out.println(studentJsonSringUsingJsonBuilder);

/*To write JSON object into a file, we need to pass a FileWriter object which is in direct implementation of Appendable interface. Make sure you call the flush() method; otherwise, the JSON file will be empty. */
String userDir = System.getProperty("user.dir");
File outputJsonFile = new File(userDir+ "\\src\\test\\resources\\StudentPayloadUsingGson.json");
FileWriter fileWriter = new FileWriter(outputJsonFile);
gsonBuilder.toJson(studentObject,fileWriter);
fileWriter.flush();
}
}

 

Output-

output

We hope you have understood everything about converting the Java object To the JSON object using Jackson API and Gson API. 🙌

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.

What is Serialization?

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

What is Deserialization?

It is the process of converting the 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

In this blog, we saw what serialization is in Rest-Assured. 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 the 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 POJO classes of a JSON Payload
Next article
POJO Class in Java
Live masterclass