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?
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.
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;
}
}
You can also try this code with Online Java Compiler
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);
}
}
You can also try this code with Online Java Compiler
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.
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;
}
}
You can also try this code with Online Java Compiler
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();
}
}
You can also try this code with Online Java Compiler
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