GroTechMinds

Serialization and Deserialization in RestAssured (1)

Serialization and Deserialization in RestAssured

A popular Java library called RestAssured facilitates communication with RESTful services during API testing. It provides an easy way to submit questions, check responses, and automate testing of APIs. One of the key components that contribute to its immense capability is its support for serialization and deserialization.

Serialization and deserialization are key concepts when working with data exchange protocols like JSON or XML. In the context of RestAssured and API testing, these terms explain how to transform Java objects to JSON (or vice versa) and vice versa. This process is necessary to automate the sending and receiving of structured data between the client and the server.

Let’s use RestAssured to take a closer look into serialization and deserialization:

blog banner

What is Serialization?

Serialization is a process where a Java object is converted into a Stream of Bytes and then we can store it in a File, database, and memory. If we want to transmit this file from one place to another place we need to convert the Object into a Stream of bytes then only we can upload it in a file or memory? In the case of RestAssured, we cannot pass the Java file directly into the body. We need to convert Java objects into a stream of bytes(JSON).

JSON Object Payload Example

				
					{

“Name” : “Tom”,
“Age” :30,
“Salary” : 56000f,
“Is Married”: true


}

				
			

We will create a Java class which have all key-value pairs, then these key values will be private members then we will create a read-write encapsulated class. These members will be private and then we will generate a getter and setter. We will set and get values accordingly we call it as POJO class. POJO stands for Plain Old Java Object. POJO is just like a regular object of Java. It will only hold the key of the class. The task of POJO is to increase the reusability of the code. It is also used to improve the readability of the code.

Creating a Payload

Create two classes in a package, “Employee Pojo” and “Create Employee”

EmployeePojo

We are now creating a POJO class that will have keys of the above(JSON Object Payload) class. We will create four different private members as we want to create an encapsulated class and set and get values. Then we will create getter and setter methods.

Please refer to our blog on Encapsulation where you can learn how to generate getter and setter methods in Java.

Encapsulation in Java

Code Snippet:

				
					package pojoex1;
public class EmployeePojo {
	private String name;
	private int age;
	private float salary;
	private boolean isMarried;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public float getSalary() {
		return salary;
	}
	public void setSalary(float salary) {
		this.salary = salary;
	}
	public boolean isMarried() {
		return isMarried;
	}
	public void setMarried(boolean isMarried) {
		this.isMarried = isMarried;
	}
}

				
			

Screenshot:

ds1

Create Employee

Now we need to prepare a body we need to follow below steps:

1. We will create an object of the EmployeePojo class as we need to convert Java objects into JSON objects.

				
					EmployeePojo emp=new EmployeePojo();
		//set all values
		emp.setName("Tom");
		emp.setAge(32);
		emp.setSalary(50000f);
		emp.setMarried(true);

				
			

2. We have to serialize the value for that we need to create a JSON  String with the help of the class ObjectMapper. The ObjectMapper class belongs to the Jackson data-bind package. It provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects). We always use the ObjectMapper class to convert Java objects into JSON. We have to add Jackson Databinding dependencies.

				
					ObjectMapper obj=new ObjectMapper();
				
			
  1. Now we will pass Java Object int ObjectMapper method.
				
					String empJson=	obj.writerWithDefaultPrettyPrinter().writeValueAsString(emp);
				
			
  1. We have now created a JSON String we pass ‘empJson’ in the body.
				
					RestAssured.baseURI="https://reqres.in";
String response=	given().log().all().headers("Content-Type" ,"application/json").body(empJson)
		.when().post("api/users")
		.then().log().all().extract().response().asString();
	System.out.println(response);
				
			

Code Snippet:

				
					import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.restassured.RestAssured;
public class CreateEmployee {
	public static void main(String[] args) throws JsonProcessingException {
		RestAssured.baseURI="https://reqres.in";
		EmployeePojo emp=new EmployeePojo();
		emp.setName("Tom");
		emp.setAge(32);
		emp.setSalary(50000f);
		emp.setMarried(true);
		ObjectMapper obj=new ObjectMapper();
		String empJson=	obj.writerWithDefaultPrettyPrinter().writeValueAsString(emp);
		String response=	given().log().all().headers("Content-Type" ,"application/json").body(empJson)
		.when().post("api/users")
		.then().log().all().extract().response().asString();
	System.out.println(response);
	}}

Output:
{
   "name": "Tom",
   "age": 32,
   "salary": 50000,
   "married": true,
   "id": "52",
   "createdAt": "2025-02-05T08:54:03.985Z"
}



				
			

Screenshot:

ds2

What is Deserialization?

The deserialization of POJO converts a JSON or XML response into a Java object (POJO) for easy manipulation of the code. We need to follow below steps:

  1. In this, we want to read the value we need to enter JSON String and enter the class name with .class extension whose value we want to read. 
				
					EmployeePojo empobj=obj.readValue(empJson,EmployeePojo.class);
				
			

2. Now we will get the values

				
					System.out.println(empobj.getName());
	System.out.println(empobj.getSalary());
	System.out.println(empobj.getAge());
	System.out.println(empobj.isMarried());



				
			

Code Snippet:

				
					public static void main(String[] args) throws JsonProcessingException {
		RestAssured.baseURI="https://reqres.in";
		EmployeePojo emp=new EmployeePojo();
		emp.setName("Tom");
		emp.setAge(32);
		emp.setSalary(50000f);
		emp.setMarried(true);
		ObjectMapper obj=new ObjectMapper();
		String empJson=	obj.writerWithDefaultPrettyPrinter().writeValueAsString(emp);
		String response=	given().log().all().headers("Content-Type" ,"application/json").body(empJson)
		.when().post("api/users")
		.then().log().all().extract().response().asString();
	System.out.println(response);
	//deserialization
	EmployeePojo empobj=obj.readValue(empJson,EmployeePojo.class);
		System.out.println(empobj.getName());
		System.out.println(empobj.getSalary());
		System.out.println(empobj.getAge());
		System.out.println(empobj.isMarried());
			
	}}
Output:
{
   "name": "Tom",
   "age": 32,
   "salary": 50000,
   "married": true,
   "id": "433",
   "createdAt": "2025-02-05T09:13:06.207Z"
}
{"name":"Tom","age":32,"salary":50000,"married":true,"id":"433","createdAt":"2025-02-05T09:13:06.207Z"}
Tom
50000.0
32
true

				
			

Screenshot:

ds3

Conclusion:

Our API testing and automation process will be a lot more accurate, streamlined, and efficient if we know how to serialize and deserialize data in RestAssured. By following this tutorial and gaining hands-on experience, you are equipping yourself with valuable knowledge that can propel your career in Software Testing Cucumber to new heights. We can improve API testing and test performance by using these tools to make sure that our requests and answers are handled consistently, maintainable, and readable.

Also Read:

Upskill Yourself
Consult Us