REST Assured Tutorial 34 – Serialization – Java Object To JSON Object Using Gson API

As a part of End to End REST Assured Tutorial, in this post, We will learn the “Serialization” concept where we will create JSON Object or Payload from Java Objects using Gson library.

We have learned about POJOs in the previous posts. If you have not refereed those posts then I will advise you to go through about POJO concepts here:-

What Is Plain Old Java Object (POJO)?

How To Create POJO Classes Of A JSON Object Payload?

How To Create POJO Classes Of A JSON Array Payload?

How To Create POJO Classes Of A Nested JSON Payload?

Now we will learn how to create JSON objects using POJOs. To create a JSON object (JSON) from Java Objects( POJOs) is called Serialization. For this, we can use any JSON parser APIs. We have learned serialization using Jackson API already. In this post, we will use the Gson Java library to serialize a Java object to JSON object.

About GSON

As per Gson official document, Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

  • Provide simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa
  • Allow pre-existing unmodifiable objects to be converted to and from JSON
  • Extensive support of Java Generics
  • Allow custom representations for objects
  • Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)

Let’s first add the latest Gson dependency in your maven project. I have used below dependency for this post which is the latest version:-



    com.google.code.gson
    gson
    2.8.6

Gson library provides a class called “Gson“. This is the main class for using Gson. Gson is typically used by first constructing a Gson instance and then invoking toJson(Object) or fromJson(String, Class) methods on it. Gson instances are Thread-safe so you can reuse them freely across multiple threads.

You can create a Gson instance by invoking new Gson(), if the default configuration is all you need. You can also use GsonBuilder to build a Gson instance with various configuration options such as versioning support, pretty-printing, custom JsonSerializer, JsonDeserializer, and InstanceCreator.

let’s learn about serialization using Gson in this post.

Target JSON Object to be created:-

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

POJO Class

Let’s create a class with field name exactly (case sensitive) the same as node names in above JSON payload because with default setting while parsing Java Object to JSON object, it will look on getter setter methods of field names. In fact, access specifiers do not matter here. We will cover some interesting facts on it later.

package SerializationDeserialization;

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

Gson class provides multiple overloaded methods called “toJson()”. Below is a glimpse:-

We will convert a Java Object to a JSON object as a String and also will write into a .json file.

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

You can download/clone the above sample project from here.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappyLearning

Find all Selenium related posts here, all API manual and automation related posts here, and find frequently asked Java Programs here.

Many other topics you can navigate through the menu.

1 thought on “REST Assured Tutorial 34 – Serialization – Java Object To JSON Object Using Gson API

Leave a Reply

Your email address will not be published. Required fields are marked *