REST Assured 35 - deserialize JSON object de serialization to Java Object using the Gson API

REST Assured series summary REST Assured 35 - use the Gson API to de serialize JSON objects into Java objects

About POJOs, when you see this article, I suggest you read the following related articles first.

What is Plain Old Java Object (POJO)?
Create a POJO as a JSON Object Payload
Create a POJO as a JSON Array Payload
Create POJO as A Nested JSON Payload

When we request an API, most of the bodies that get the response are JSON or XML. We can use Jsonpath or Xmlpath to traverse the returned response body to obtain some special values, but this is not recommended if the response is too large or nested too deeply. We can also parse JSON or XML responses into POJO classes, which makes it easier to get the value of any field, which is called de serialization. We can use any JSON parser APIs. In this article, we use the Gson API to deserialize. Earlier, we learned about using Jackson API to serialization and De serialization deserialization And use Gson API serialization.

About GSON
according to Gson official documents , gson is a Java library used to convert Java Objects into JSON, or convert a JSON string into an equivalent Java Object. Gson can also serve any Java Objects, including pre-existing objects without source code.

  1. Simple toJson() and fromJson() methods are provided for the conversion of Java Objects and JSON.
  2. Allow the conversion of pre-existing immutable objects to JSON
  3. Extensive support for Java generics
  4. Allow custom objects to express representations
  5. Supports arbitrarily complex objects (deep inheritance structures and generics)

add to Gson latest dependency package:

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.8</version>
</dependency>

The Gson library provides a Gson class, which is the main class of Gson. Before calling the tojason (object) or fromjason (string, class) method, create an instance of the Gson class. The Gson instance is thread safe and can be used for multithreading.

You can call Gson() to create a Gson instance. If the default configuration can meet your needs. You can also use GsonBuilder to create Gson instances with different configurations, such as version configuration, pretty printing, custom JsonSerializer and JsonDeserializer.

JSON String

{
  "firstName" : "Amod",
  "lastName" : "Mahajan",
  "gender" : "M",
  "age" : 29,
  "salary" : 10987.77,
  "married" : false
}

POJO class

Let's create a class. The field name remains the same as the node name in the JSON payload above (case sensitive), because when parsing a Java Object into a JSON object, we will view the getter setter method of the field. It doesn't matter much to access the property here.

public class Employee {
 
	private String firstName;
	private String lastName;
	private String gender;
 
	private int age;
	private double salary;
	private boolean married;
 
	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 getGender() {
		return gender;
	}
 
	public void setGender(String gender) {
		this.gender = gender;
	}
 
	public int getAge() {
		return age;
	}
 
	public void setAge(int age) {
		this.age = age;
	}
 
	public double getSalary() {
		return salary;
	}
 
	public void setSalary(double salary) {
		this.salary = salary;
	}
 
	public boolean getMarried() {
		return married;
	}
 
	public void setMarried(boolean married) {
		this.married = married;
	}
 
}

JSON Sring to POJO

The Gson class provides many overridden fromjason () methods.

We will learn how to reverse sequence a string and a. Json file into a Java object. The following Json files are prepared

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\" : \"Amod\",\r\n" + "  \"lastName\" : \"Mahajan\",\r\n"
				+ "  \"gender\" : \"M\",\r\n" + "  \"age\" : 29,\r\n" + "  \"salary\" : 10987.77,\r\n"
				+ "  \"married\" : false\r\n" + "}";
 
		Gson gson = new Gson();
		// Pass JSON string and the POJO class
		Employee employeeObject = gson.fromJson(jsonString, Employee.class);
		// Now use getter method to retrieve values
		String firsName = employeeObject.getFirstName();
		String lastName = employeeObject.getLastName();
		String gender = employeeObject.getGender();
		int age = employeeObject.getAge();
		double salary = employeeObject.getSalary();
		boolean married = employeeObject.getMarried();
 
		System.out.println("Details of Employee is as below:-");
		System.out.println("First Name : " + firsName);
		System.out.println("Last Name : " + lastName);
		System.out.println("Gender : " + gender);
		System.out.println("Age : " + age);
		System.out.println("Salary : " + salary);
		System.out.println("Married : " + married);
 
		// De-serializing from a json file
		String userDir = System.getProperty("user.dir");
		File inputJsonFile = new File(userDir + "\\src\\test\\resources\\EmployeePayloadUsingGson.json");
		FileReader fileReader = new FileReader(inputJsonFile);
		Employee employeeObject1 = gson.fromJson(fileReader, Employee.class);
 
		// Now use getter method to retrieve values
		String firsName1 = employeeObject1.getFirstName();
		String lastName1 = employeeObject1.getLastName();
		String gender1 = employeeObject1.getGender();
		int age1 = employeeObject1.getAge();
		double salary1 = employeeObject1.getSalary();
		boolean married1 = employeeObject1.getMarried();
 
		System.out.println("Details of Employee from json file is as below:-");
		System.out.println("First Name : " + firsName1);
		System.out.println("Last Name : " + lastName1);
		System.out.println("Gender : " + gender1);
		System.out.println("Age : " + age1);
		System.out.println("Salary : " + salary1);
		System.out.println("Married : " + married1);
	}
}

Output:

Details of Employee is as below:-
First Name : Amod
Last Name : Mahajan
Gender : M
Age : 29
Salary : 10987.77
Married : false
Details of Employee from json file is as below:-
First Name : Amod
Last Name : Mahajan
Gender : M
Age : 29
Salary : 10987.77
Married : false

Tags: JSON API testing

Posted on Sat, 11 Sep 2021 19:17:34 -0400 by teng84