Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
De-Serialization – A JSON Object To A Java Object Using Jackson API
2.1.
About Jackson API
2.1.1.
Class ObjectMapper
2.2.
JSON String To POJO
3.
De-Serialization – JSON Object To A Java Object Using Gson API
3.1.
About GSON
3.2.
JSON String TO POJO
4.
Frequently Asked Questions
4.1.
What is POJO?
4.2.
Why is Serialization?
4.3.
Why is Deserialization?
4.4.
Can a Serialized object be transferred via a network?
4.5.
What is JSON Payload? 
5.
Conclusion
Last Updated: Mar 27, 2024
Medium

De-Serialization – JSON Object To Java 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 is De-Serialization? It is the process of converting a JSON object to a POJO object. But do you know how to convert a JSON object to a Java object using Jackson API and Gson API in Rest-Assured? No worries, in this article we will learn about how to convert JSON Object into a Java object using Jackson API and Gson API.

how to convert JSON Object into a JAVA object using Jackson API and Gson API

Fine! So let us learn how to convert a JSON object to a Java object using Jackson API and Gson API.💫

De-Serialization – A JSON Object To A Java Object Using Jackson API

Let’s learn how to convert a JSON object to Java object using Jackson API.

About Jackson API

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

We must include Jackson API in the Java project build path in order to use it. You can either download a jar file with transitive jars or add 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 is this one, and that is how long we will use it. A Java object can be converted to a JSON object and vice versa using the ObjectMapper class. This article will show you how to translate a Java object into a JSON object using the ObjectMapper class.

Target JSON string:-

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

 

We must convert the preceding JSON string to a Java object. A class, such as one or more POJO classes, is required in order to create a Java object, depending on the requirement. Create a class with field names that are exactly (case-sensitively) the same as the node names in the preceding JSON string because by default, when parsing a JSON object into a Java object, the getter setter methods of the fields are what are used.

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

 

For various purposes, the ObjectMapper class offers a variety of readValue() methods that are overloaded. Getting JSON from a file or as a string, which is what you'll typically see. This method will compare the fields in the passed POJO class with the fields in the JSON string and use setter methods to set values that are simple to retrieve using getter methods.

JSON String To POJO

For various purposes, the ObjectMapper class offers a variety of readValue() methods that are overloaded. Getting JSON from a file or as a string is what you'll typically see. This method will compare the fields in the passed POJO class to the fields in the JSON string and use setter methods to set values that are simple to retrieve using getter methods.

package SerializationDeserialization;
 
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
 
public class DeserializeJsonToJava {
 
	public static void main(String[] args) throws JsonMappingException, JsonProcessingException {

		String JSONString = "{\r\n" + 
		"  \"firstName\" : \"Akshat\",\r\n" + 
		"  \"lastName\" : \"Agarwal\",\r\n" + 
		"  \"subject\" : \"Data structures and algorithms\",\r\n" + 
		"  \"school\" : \"Coding Ninjas\",\r\n" + 
	}";

	ObjectMapper objectMapper = new ObjectMapper();
	// Pass JSON string and the POJO class 
	Student studentObject = objectMapper.readValue(JSONString, Student.class);
	// Now use getter method to retrieve values
	String firstName = studentObject.getFirstName();
	String lastName = studentObject.getLastName();
	String subject = studentObject.getSubject();
	String school = studentObject.getSchool();


	System.out.println("Details of student is as below:-");
	System.out.println("First Name : "+firsName);
	System.out.println("Last Name : "+lastName); 
	System.out.println("Subject Name : "+subject); 
	System.out.println("School Name : "+school); 
	}
}

 

Output - 

Output
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

De-Serialization – JSON Object To A Java Object Using Gson API

Now, in this section, we will learn how to convert a JSON object to a Java object using Gson API.

About GSON

The Gson Java library transforms Java Objects into their JSON representation. Additionally, it can be used to translate a JSON string into a corresponding Java object. Gson can operate on any Java object, even ones for which you don't have the source code.

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

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

👉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 is offered by the Gson library. In order to use Gson, you need to typically create a Gson instance first, then call the toJson(Object) or fromJson(String, Class) methods on it. Because Gson instances are thread-safe, you can freely reuse them across various threads.

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

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

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

 

Target JSON String to be created:-

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

 

We need to convert the preceding JSON string to a Java object. A class, such as one or more POJO classes, is required in order to create a Java object, depending on the requirement. Create a class with field names that are exactly (case-sensitively) the same as the node names in the preceding JSON string. Because by default when parsing a JSON object into a Java object, the getter and setter methods of the fields are used. Access specifiers are actually irrelevant in this case. 

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

JSON String TO POJO

This section will discover how to convert a JSON string and.json file into Java objects.

package SerializationDeserialization;
 
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
 
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.google.gson.Gson;
 
public class DeserializeJsonToJavaObjectUsingGson {
 
	public static void main(String[] args) throws JsonMappingException, JsonProcessingException, FileNotFoundException {
 	
		// De-serializing from JSON String
		String JSONString = "{\r\n" + 
		"  \"firstName\" : \"Akshat\",\r\n" + 
		"  \"lastName\" : \"Agarwal\",\r\n" + 
		"  \"subject\" : \"Data structures and algorithms\",\r\n" + 
		"  \"school\" : \"Coding Ninjas\",\r\n " +"}";
 		
		Gson gson = new Gson();
		// Pass JSON string and the POJO class
		Student studentObject = gson.fromJson(JSONString, Student.class);
		// Now use getter method to retrieve values
		String firstName = studentObject.getFirstName();
		String lastName = studentObject.getLastName();
		String subject = studentObject.getSubject();
		String school = studentObject.getSchool();
 		
		System.out.println("Details of Student is as below:-");
		System.out.println("First Name : "+firstName);
		System.out.println("Last Name : "+lastName); 
		System.out.println("Subject Name : "+subject); 
		System.out.println("School Name : "+school); 
 		
		// De-serializing from a json file
		String userDir = System.getProperty("user.dir");
		File inputJsonFile = new File(userDir + "\\src\\test\\resources\\StudentPayloadUsingGson.json");
		FileReader fileReader = new FileReader(inputJsonFile);
		Student studentObject1 = gson.fromJson(fileReader, Student.class);
 		
		// Now use getter method to retrieve values
		String firstName1 = studentObject.getFirstName();
		String lastName1 = studentObject.getLastName();
		String subject1 = studentObject.getSubject();
		String school1 = studentObject.getSchool();


 		
		System.out.println("Details of Student from json file is as below:-");
		System.out.println("First Name : "+firstName1);
		System.out.println("Last Name : "+lastName1); 
		System.out.println("Subject Name : "+subject1); 
		System.out.println("School Name : "+school1); 
	}
}

 

Output- 

Output

We hope you have understood everything about de-serialization - how to convert a JSON object To a Java 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 as well as 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

In this blog, we learned about De-Serialization 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 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
POJO Class in Java
Next article
Ignore Default and Null values in Payload in Rest Assured
Live masterclass