How to test JSON Request using GSON API


In this tutorial, I will explain the testing of a JSON Payload using GSON API.

Refer to the below tutorials to understand how GSON works:-

Serialization – How to convert Java Object To JSON Object Using Gson API

Deserialization – How to create JSON Object to JAVA Object Using Gson API

Add below dependency to POM.xml to use Gson API.


As we know, we can use toJson() to convert the JAVA objects to JSON Payload.

In the below example, I have created a POJO class with the name of EmployeeDetails. This class contains the data members corresponding to the JSON nodes and their corresponding getter and setter methods.

public class EmployeeDetails {

	// private variables or data members of pojo class
	private String name;
	private double salary;
	private int age;

	public String getName() {
		return name;

	public void setName(String name) { = name;

	public double getSalary() {
		return salary;

	public void setSalary(double salary) {
		this.salary = salary;

	public int getAge() {
		return age;

	public void setAge(int age) {
		this.age = age;


Below, will create a JSON payload and pass it as a request body to the Rest API.

	public void createEmployee() throws IOException {

		// Just create an object of Pojo class
		EmployeeDetails emp = new EmployeeDetails();

		// Converting a Java class object to a JSON payload as string using Gson
		Gson builder = new GsonBuilder().setPrettyPrinting().create();
		String employeePrettyJsonPayload = builder.toJson(emp);

		// GIVEN

		// WHEN

		// THEN
              .body("status", equalTo("success"))
			  .body("", equalTo("GsonTest"))
              .body("data.salary", equalTo(50000))
			  .body("data.age", equalTo(25))
              .body("message", equalTo("Successfully! Record has been added."))



We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s