REST Assured 34 - serialize Java objects into JSON objects using the Gson API

Posted by perrio on Sun, 12 Sep 2021 07:41:15 +0200

REST Assured series summary REST Assured 34 - serialize Java objects into JSON objects using the Gson API

We have learned about POJOs before. 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

Now we will use POJOs to create JSON Objects. Creating Java Objects (POJOs) into a JSON object (JSON) is called serialization. In the previous article, we have learned how to use Jackson API serialization This article will introduce how to serialize a Jason Object into a JSON Object with the Gson Java library.

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.

Target JSON Object

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

POJO to JSON String

The Gson class provides the toJson() method of polyphase Rewriting:

We convert a Java Object into a json string and write it to a. json file.

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 Employee java object
		Employee employeeObject = new Employee();
		employeeObject.setFirstName("Amod");
		employeeObject.setLastName("Mahajan");
		employeeObject.setAge(29);
		employeeObject.setSalary(10987.77);
		employeeObject.setMarried(false);
		employeeObject.setGender("M");
		
		// Create a Gson object
		Gson gson = new Gson();
		// toJson(Object src) method converts Java object to JSON object
		String employeeJsonSring = gson.toJson(employeeObject);
		// Printing json string. It will be pretty print 
		System.out.println("Non-pretty JSON String :- ");
		System.out.println(employeeJsonSring);
		
		// We can create a configurable Gson instance using GsonBuilder class
		Gson gsonBuilder = new GsonBuilder().setPrettyPrinting().create();
		String employeeJsonSringUsingJsonBuilder = gsonBuilder.toJson(employeeObject);
		System.out.println("Pretty JSON String :- ");
		System.out.println(employeeJsonSringUsingJsonBuilder);
		
		// To write Json object in to a file, we need to pass a FileWriter object which is in direct implementation of 
		// Appendable interface. Make sure you call flush() method otherwise json file will be empty.
		String userDir = System.getProperty("user.dir");
		File outputJsonFile = new File(userDir+ "\\src\\test\\resources\\EmployeePayloadUsingGson.json");
		FileWriter fileWriter = new FileWriter(outputJsonFile);
		gsonBuilder.toJson(employeeObject,fileWriter);
		fileWriter.flush();
		
	}
}

Output:

Non-pretty JSON String :- 
{"firstName":"Amod","lastName":"Mahajan","gender":"M","age":29,"salary":10987.77,"married":false}
Pretty JSON String :- 
{
  "firstName": "Amod",
  "lastName": "Mahajan",
  "gender": "M",
  "age": 29,
  "salary": 10987.77,
  "married": false
}

Generated JSON file:

Topics: JSON API testing gson