Serialization – How to create JSON Payload from Java Object – Jackson API

HOME

In this tutorial, I will explain the creation of JSON Object Payload with the help of POJO (Plain Old Java Object).

What is POJO?

POJO stands for Plain Old Java Object. It is a very simple object, and it has no bounds or we can say that it has no restrictions other than the Java language specification. Also, it does not require any classpath.

A big advantage of POJO is it increases the readability and reusability of our project code and developers find it easy when understanding the code. Also, POJO is easy to write and anyone can understand them easily.

Now let’s deep dive into some technical terms about the POJO. Below are a few points about the POJO are:

  1. A POJO should not have to extend prespecified classes.
  2. Secondly, a POJO should not have implemented any prespecified interface.
  3. Lastly, POJO should not contain prespecified annotations

A POJO class can follow some rules for better usability. These rules are:-

  1. Each variable should be declared as private just to restrict direct access.
  2. Each variable that needs to be accessed outside class may have a getter, a setter, or both methods. If the value of a field is stored after some calculations, then we must not have any setter method for that.
  3. It Should have a default public constructor.
  4. Can override toString(), hashcode, and equals() methods.

POJO classes are extensively used for creating JSON and XML payloads for API.

In the below example, let me create a simple JSON with some nodes which is actually a 1:1 mapping i.e. each key has a single value, and the type of values is mixed.

{
  "firstName" : "Vibha",
  "lastName" : "Singh",
  "age" : 30,
  "salary" : 75000.0,
  "designation" : "Manager",
  "contactNumber" : "+91999996712",
  "emailId" : "abc123@test.com"
}

Let us create variables in the POJO class now for the above JSON. Now, a class name Employee will be created with the private data members as mentioned in the above JSON. Since we have created all variables as private, then there should be a way to manipulate or retrieve these data. So we create the corresponding getter and setter methods for these data members.

It is very tedious to create getter and setter methods for all the data members for big JSON strings.  Every IDE gives you a shortcut to generate getter and setter methods.  Here, I am using Eclipse and creating these getter and setter methods.

Select all the data members and Right-click on the page. Then select Source and then select Generate Getter and Setter methods.

This opens a new screen as shown below.

You can select the data member for which you want to create the getter and setter method. I want to create the getter and setter methods for all the data members, so click on Select All and then click on the Generate Button. This will generate the getter and setter methods for all the data members.

Below is the sample code of the Employee table, which contains the data members needed for Employee JSON and their corresponding getter and setter methods.

public class Employee {

	// private variables or data members of POJO class
	private String firstName;
	private String lastName;
	private int age;
	private double salary;
	private String designation;
	private String contactNumber;
	private String emailId;

	// Getter and setter methods
	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 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 String getDesignation() {
		return designation;
	}

	public void setDesignation(String designation) {
		this.designation = designation;
	}
	
	public String getContactNumber() {
		return contactNumber;
	}

	public void setContactNumber(String contactNumber) {
		this.contactNumber = contactNumber;
	}

	public String getEmailId() {
		return emailId;
	}

	public void setEmailId(String emailId) {
		this.emailId = emailId;
	}

}

Using the above POJO class, you can create any number of custom Employee objects and each object can be converted into a JSON Object and Each JSON object can be parsed into Employee POJO.

We will create a JSON object from POJO and vice versa now, which is generally called serialization and deserialization using Jackson APIs.

Serialization – Serialization is a process where you convert an Instance of a Class (Object of a class) into a Byte Stream. Here, we are converting Employee class object to JSON representation or Object

Deserialization – It is the reverse of serializing. In this process, we will read the Serialized byte stream from the file and convert it back into the Class instance representation. Here, we are converting a JSON Object to an Employee class object.

We are using Jackson API for Serialization and Deserialization. So, add the Jackson dependency to the project.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.0</version>
</dependency>

What is ObjectMapper ?

ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model (JsonNode), as well as related functionality for performing conversions. It is also highly customizable to work both with different styles of JSON content and to support more advanced object concepts such as polymorphism and object identity.

Now, let us create a Test Class to show Serialization.

public class EmployeeTest {

	@Test
	public void serializationTest()  {

		Employee employee = new Employee();
		employee.setFirstName("Vibha");
		employee.setLastName("Singh");
		employee.setAge(30);
		employee.setSalary(75000);
		employee.setDesignation("Manager");

		// Converting a Java class object to a JSON payload as string
		ObjectMapper mapper = new ObjectMapper();
		String employeeJson = mapper.writeValueAsString(employee);
		String employeePrettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee);
		System.out.println(employeeJson);
		System.out.println(employeePrettyJson);
   }
}try {
			String employeeJson = mapper.writeValueAsString(employee);
			System.out.println(employeeJson);
			String employeePrettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee);
			System.out.println(employeePrettyJson);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}	
	}

The output of the above program is

Here, ObjectMapper from fasterxml.jackson.databind is used for Serialization.

writeValueAsString() is a method that can be used to serialize any Java value as a String.

writerWithDefaultPrettyPrinter() is used to pretty-print the JSON output. It is a Factory method for constructing ObjectWriter that will serialize objects using the default pretty printer for indentation.

I hope this has helped to clear your doubts regarding POJO and how to create JSON objects using POJO.

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

How to test POST JSON Object request using Java Map in Rest Assured

HOME

In the last tutorial, I explained How to test POST request from JSON Object in Rest Assured where the request body is built in JSONObject. In this tutorial, I will create a request body using JSON Object in Rest Assured. 

We can create a JSON Object using a Map in Java. A JSON Object is a key-value pair and can be easily created using a Java Map. A Map in Java also represents a collection of key-value pairs.

<dependencies>

    <dependency>
      <groupId>org.json</groupId>
      <artifactId>json</artifactId>
      <version>20231013</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.1</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>io.rest-assured</groupId>
      <artifactId>rest-assured</artifactId>
      <version>5.3.2</version>
      <scope>test</scope>
    </dependency>
    
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.15.2</version>
    </dependency>

  </dependencies>

I have created a simple Java map and filled it with the values that represent JSON properties.

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.Matchers.equalTo;

public class Json_Demo {

    @Test
    public void passBodyAsMap() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("employee_name", "MapTest");
        map.put("employee_salary", "99999");
        map.put("employee_age", "30");
        map.put("profile_image", "test.png");
        RestAssured.given()
                .contentType(ContentType.JSON)
                .body(map)
                .log().all()

                .when()
                .post("https://dummy.restapiexample.com/api/v1/create")

                .then()
                .assertThat().statusCode(200)
                .body("data.employee_name", equalTo("MapTest"))
                .body("data.employee_age", equalTo("30"))
                .body("data.employee_salary", equalTo("99999"))
                .body("message", equalTo("Successfully! Record has been added.")).log().all();
    }
}

The request body as well as the response body will look as shown below:-

Above one is a simple JSON Request Body. Let us take an example of a Complex Request Body or nested Request Body as shown below.

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.Matchers.equalTo;

public class Json_Demo {

    @Test
    public void passBodyAsMultipleMap() {

        // First JSON Object using Hash Map
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("employee_name", "MapTest");
        data.put("profile_image", "test.png");

        // Second JSON Object using Hash Map
        Map<String, String> msg = new HashMap<String, String>();
        msg.put("updated_message", "Details of New Resource");
        msg.put("employee_age", "30");
        data.put("details", msg);
        data.put("employee_salary", "99999");
        RestAssured.given().contentType(ContentType.JSON).body(data).log().all()
                // WHEN
                .when().post("https://dummy.restapiexample.com/api/v1/create")
                // THEN
                .then().assertThat().statusCode(200).body("data.employee_name", equalTo("MapTest"))
                .body("data.details.updated_message", equalTo("Details of New Resource"))
                .body("data.details.employee_age", equalTo("30")).body("data.employee_salary", equalTo("99999"))
                .body("message", equalTo("Successfully! Record has been added.")).log().all();
    }
}

The request body as well as the response body will look as shown below image. The first part is the body of the request and the second part is the response provided by the API.

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

Rest Assured Tutorials

HOME

RestAssured is a Java-based library that is used to test RESTful Web Services. REST-assured was designed to simplify the testing and validation of REST APIs. It takes influence from testing techniques used in dynamic languages such as Ruby and Groovy.

Chapter 1 Assertion of JSON in Rest Assured using Hamcrest
Chapter 2 Extraction from JSON in Rest Assured – JsonPath
Chapter 3 How to perform multiple assertions in Rest Assured? 
Chapter 4 How to validate JSON body in Rest Assured?
Chapter 5 Compare JSON Objects using JSONAssert Library
Chapter 6 Compare JSON Arrays using JSONAssert Library
Chapter 7 How to Read JSON with JSON.simple – NEW
Chapter 8 How to create and write to JSON with JSON.simple – NEW

JSON Handling and manipulation

Category 10: XML Manipulations

XML Handling and manipulation

Gradle

Chapter 1 Setup Basic REST Assured Gradle Project In Eclipse IDE

Frameworks

Chapter 1 Integration of REST Assured with TestNG
Chapter 2 Integration of REST Assured with JUnit4
Chapter 3 Integration of REST Assured with JUnit5
Chapter 4 Serenity BDD with Cucumber and Rest Assured
Chapter 5 Serenity BDD with Cucumber and Rest Assured in Gradle
Chapter 6 How To Create Gradle Project with Cucumber to test Rest API
Chapter 7 Rest API Test in Cucumber and JUnit4
Chapter 8 API Automation with REST Assured, Cucumber and TestNG

How to create JSON Array Request Body – org.json

Last Updated On

HOME

In the last tutorial, I explained How to test POST JSON Object request using Java Map in Rest Assured. In this tutorial, I will create a request body using JSON Array in Rest Assured. This request body can be used for POST or PUT operations.

Table of Contents

  1. What is JSONArray?
  2. How to create JSONArray Request Body or payload?
  3. Complex JSON Array

What is JSONArray?

JSONArray represents an immutable JSON array (an ordered sequence of zero or more values). It also provides an unmodifiable list view of the values in the array.

  1. JSON array can store multiple value types. The values in a JSONArray can be of the following types: JsonObject, JsonArray, JsonString, JsonNumber, JsonValue.TRUE, JsonValue.FALSE, and JsonValue.NULL.
  2. The array index begins with 0.
  3. The square brackets [ ] are used to declare the JSON array.

An API can accept a JSON Array payload as a request body. Imagine, we want to add employee details of more than one employee in the below example. In this case, we can pass multiple JSON objects within a JSON array. I have explained 2 ways to create JSON Object – map or JsonObject. Refer to any one of the tutorials to get to know about the creation of JSON Object.

To create a JSON Array, we need to add org.json Maven dependency, as shown below. The latest version can be found here.

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20240303</version>
</dependency>  

JSONObject is imported from the package:

import org.json.JSONObject;

JSONArray is imported from the package:

import org.json.JSONArray;

Below is an example of JSONArray.

How to create JSONArray Request Body or payload?

  1. Create a JSON Object and add the first employee details.
  2. Create another JSON Object and add second guest details.
  3. Create a JSONArray.
  4. Add both JSON Objects to JSONArray.

Below is an example of creating a request from JSONArray with multiple JSON Objects.  I am using a logger just to print the JSON body in the Console. 

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;

public class Json_Demo {

    @Test
    public void passBodyAsJsonArrayDemo() {

        // JSON Object for first employee
        JSONObject data1 = new JSONObject();

        data1.put("employee_name", "ObjectTest");
        data1.put("profile_image", "test1.png");
        data1.put("employee_age", "30");
        data1.put("employee_salary", "11111");

        // JSON Object for second employee
        JSONObject data2 = new JSONObject();

        data2.put("employee_name", "MapTest");
        data2.put("profile_image", "test2.png");
        data2.put("employee_age", "20");
        data2.put("employee_salary", "99999");

        // Creating JSON array to add both JSON objects
        JSONArray array = new JSONArray();
        array.put(data1);
        array.put(data2);

        // Send the request
        RestAssured.given()
                .contentType(ContentType.JSON)
                .body(array.toString())
                .log().all()

                .when()
                .post("https://dummy.restapiexample.com/api/v1/create")

                .then()
                .assertThat().statusCode(200)
                .body("message", equalTo("Successfully! Record has been added."))
                .log().all();
    }
}

The output of the above program is

       // JSON Object for first employee
        JSONObject data1 = new JSONObject();

        data1.put("employee_name", "ObjectTest");
        data1.put("profile_image", "test1.png");
        data1.put("employee_age", "30");
        data1.put("employee_salary", "11111");

        // JSON Object for second employee
        JSONObject data2 = new JSONObject();

        data2.put("employee_name", "MapTest");
        data2.put("profile_image", "test2.png");
        data2.put("employee_age", "20");
        data2.put("employee_salary", "99999");
JSONArray array = new JSONArray();
array.put(data1);
array.put(data2);
contentType(ContentType.JSON)
.body(array.toString())
.log().all()
.post("https://dummy.restapiexample.com/api/v1/create")
.assertThat().statusCode(200)
.body("message", equalTo("Successfully! Record has been added."))
.log().all()

Complex JSON Array

Let us see an example of a complex JSON Array. This structure represents two separate employee data sets. Each is contained within its own JSON array. The whole is encapsulated within a larger JSON object identified by keys employee1 and employee2.


{
    "employee1": [
      {
        "firstname": "Tom",
        "salary": 720000,
        "age": 59,
        "lastname": "Mathew"
     }
    ],
    "employee2": [
     {
        "firstname": "Perry",
        "salary": 365000,
        "age": 32,
        "lastname": "David"
    }
   ]
}

The above JSON Array can be created as

import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;

public class Json_Demo {

    @Test
    public void passBodyAsJsonArray() {

        // JSON Object for first employee
        JSONObject data1 = new JSONObject();

        data1.put("firstname", "Tom");
        data1.put("lastname", "Mathew");
        data1.put("age", 59);
        data1.put("salary", 720000);

        // JSON Object for second employee
        JSONObject data2 = new JSONObject();

        data2.put("firstname", "Perry");
        data2.put("lastname", "David");
        data2.put("age", 32);
        data1.put("salary", 365000);

        // Creating first JSON array
        JSONArray array1 = new JSONArray();
        array1.put(data1);

        // Creating second JSON array
        JSONArray array2 = new JSONArray();
        array2.put(data2);

        // Create JSON Object to add both JSONArrays
        JSONObject data3 = new JSONObject();
        data3.put("employee1", array1);
        data3.put("employee2", array2);

        System.out.println(data3.toString(4));

    }
}

JSONObject data1 = new JSONObject();
data1.put("firstname", "Tom");
data1.put("lastname", "Mathew");
data1.put("age", 59);
data1.put("salary", 720000);

JSONObject data2 = new JSONObject();
data2.put("firstname", "Perry");
data2.put("lastname", "David");
data2.put("age", 32);
data2.put("salary", 365000);

JSONArray array1 = new JSONArray();
array1.put(data1);

JSONArray array2 = new JSONArray();
array2.put(data2);

A third JSONObject, data3, is created to aggregate the two JSON arrays under separate keys: employee1 and employee2.

JSONObject data3 = new JSONObject();
data3.put("employee1", array1);
data3.put("employee2", array2);
System.out.println(data3.toString(4));

Similarly, there is another way to create this JSON Structure.

import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;

public class Json_Demo {

    @Test
    public void passBodyAsJsonArray1() {

        // Creating JSON array to add first JSON object
        JSONArray array1 = new JSONArray();
        array1.put(new JSONObject().put("firstname", "Tom").put("lastname", "Mathew").put("age", 59).put("salary",
                720000));

        // Creating JSON array
        JSONArray array2 = new JSONArray();
        array2.put(new JSONObject().put("firstname", "Perry").put("lastname", "David").put("age", 32).put("salary",
                365000));

        // Create JSON Object to add JSONArrays
        JSONObject data1 = new JSONObject();
        data1.put("employee1", array1);
        data1.put("employee2", array2);

        System.out.println(data1.toString(4));

    }
}

The output of the above program is

Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!

Deserialization – How to convert JSON to Map using Jackson API

HOME

This tutorial shows how to convert JSON to JAVA map using Jackson’s data binding. In the previous tutorials, I have explained converting Java Objects/Arrays to JSON String using Jackson API. You can refer below tutorials.

Serialization – How to create JSON Payload from Java Object – Jackson API

Deserialization – How to convert JSON to Java Object using Jackson API

How to create JSON Array Payload using POJO – Jackson API

How to create Nested JSON Object using POJO – Jackson API

To start with, we need to add Jackson Maven Dependency to the POM. Always add the latest version of Jackson dependency to your project.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.0</version>
</dependency

Deserialization converts a stream of bytes into a Java object that we can use in code.

We use Jackson’s ObjectMapper, as we did for serialization, using readValue() to process the input. Also, note our use of Jackson’s TypeReference, which we’ll use in all of our deserialization examples to describe the type of our destination Map.

   @Test
	public void DeserializationMapTest() throws JsonProcessingException {

		String employeeString = 
                     "{\r\n" 
                    + "  \"firstName\" : \"Deserialization\",\r\n"
				    + "  \"lastName\" : \"Test\",\r\n" 
                    + "  \"age\" : 25,\r\n" 
                    + "  \"salary\" : 50000.0,\r\n"
				    + "  \"designation\" : \"Manager\",\r\n" 
                    + "  \"contactNumber\" : \"+918882211111\",\r\n"
				    + "  \"emailId\" : \"abc@test.com\",\r\n" 
                    + "  \"gender\" : \"female\",\r\n"
				    + "  \"maritalStatus\" : \"single\"\r\n" 
                    + " }";

		Map<String, String> resultMap = new HashMap<String, String>();
		ObjectMapper mapper = new ObjectMapper();

		// Converting a JSON to Java Map
		try {
			resultMap = mapper.readValue(employeeString, new TypeReference<HashMap<String, String>>() {
			});
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}

		System.out.println("Output Map :" + resultMap);
	}

Output

We can get the JSON from a file and convert it to a Hash Map too. Below is an example of the same.

   @Test
	public void PayloadFromFile() {

		String userDir = System.getProperty("user.dir");
		ObjectMapper mapper = new ObjectMapper();

		// Converting Employee JSON string to Employee class object
		Map<String, Object> empMap;
		try {
			empMap = mapper.readValue(new File(userDir + "\\src\\test\\resources\\JSONFromMap.json"),
					new TypeReference<Map<String, Object>>() {
					});

			System.out.println("Gender : " + empMap.get("gender"));
			System.out.println("DOB : " + empMap.get("DOB"));
			System.out.println("Name : " + empMap.get("name"));
			System.out.println("ContactNumber : " + empMap.get("contactNumber"));
			System.out.println("SkillSet : " + empMap.get("skillset"));
		} catch (StreamReadException e) {
			e.printStackTrace();
		} catch (DatabindException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

Output

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

Serialization – How to convert Map to JSON string using Jackson API

HOME

This tutorial shows how to convert a Java map to JSON string using Jackson’s data binding. In the previous tutorials, I explained converting Java Objects/Arrays to JSON String using Jackson API. You can refer to the below tutorials.

Serialization – How to create JSON Payload from Java Object – Jackson API

How to create JSON Array Payload using POJO – Jackson API

How to create Nested JSON Object using POJO – Jackson API

To start off, add the latest Jackson dataformat Maven dependency to the project.

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.13.0</version>
</dependency>

Sample JSON

{
  "skillset" : [ 
                 "Java",
                 "Teradata",
                 "Python", 
                 "Power BI" 
               ],
  "gender" : "female",
  "DOB" : "12-02-1985",
  "name" : "Vibha Singh",
  "contactNumber" : "+919999988822",
  "employeeId" : "10342256",
  "location" : "Dublin",
  "emailId" : "abc@test.com",
  "salary" : "75000.0"
}

First, we will populate a Map, then convert them into JSON and later write that JSON to a file.

	@Test
	public void SerializationMapTest() {

		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> inputMap = new HashMap<String, Object>();

		inputMap.put("employeeId", "10342256");
		inputMap.put("name", "Vibha Singh");
		inputMap.put("DOB", "12-02-1985");
		inputMap.put("salary", "75000.0");
		inputMap.put("location", "Dublin");
		inputMap.put("contactNumber", "+919999988822");
		inputMap.put("emailId", "abc@test.com");
		inputMap.put("gender", "female");

		List<String> skillset = new ArrayList<String>();

		skillset.add("Java");
		skillset.add("Teradata");
		skillset.add("Python");
		skillset.add("Power BI");

		inputMap.put("skillset", skillset);

		// Converting map to a JSON payload as string
		try {
			String employeePrettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(inputMap);
			System.out.println(employeePrettyJson);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}

		String userDir = System.getProperty("user.dir");

        //Writing JSON on a file
		try {
			mapper.writerWithDefaultPrettyPrinter()
					.writeValue(new File(userDir + "\\src\\test\\resources\\JSONFromMap.json"), inputMap);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}

Output

As mentioned above, the new JSON is saved in a file and placed under src/test/resources.

Below is the file with JSON.

Congratulations, we are done. We have successfully created a JSON using HashMap.

Rest Assured – How to test JSON Request using Jackson API

HOME

This tutorial focuses on the testing of a REST API (with JSON payload). We will use Jackson API to serialize the request.

It is suggested to go through these tutorials to understand about creating a JSON Object Payload using POJO (Plain Old Java Object).

How to create JSON Object Payload using POJO – Jackson API

How to create JSON Array Payload using POJO – Jackson API

How to create Nested JSON Object using POJO – Jackson API

To start with, we need to add Jackson Maven’s Dependency to the POM. Always add the latest version of Jackson dependency to your project.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.17.2</version>
</dependency>

The complete POM.xml will look like this, as shown below:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>RestAssured_JUnit4_Demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <rest-assured.version>5.3.0</rest-assured.version>
        <junit.version>4.13.2</junit.version>
        <jackson.version>2.17.2</jackson.version>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <dependencies>

        <!-- Rest-Assured Dependency -->
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>${rest-assured.version}</version>
            <scope>test</scope>
        </dependency>

        <!-- JUnit4 Dependency -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>

        <!-- Jackson Dependency -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>

        <!-- Hamcrest Dependency -->
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-all</artifactId>
            <version>1.3</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>

This dependency will also transitively add the following libraries to the classpath:

  1. jackson-annotations
  2. jackson-core

In the below example, let us assume that we need to create a new Employee (POST Request). To start with, we need to create a POJO class of the JSON payload (EmployeeDetails). This POJO class should contain 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;

    // Getter and Setters
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.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;
	}

}

Now that we have our POJO class, we can start writing some REST Assured Serialization tests!

Let’s start with REST Assured Serialization with JSON. I want to send a POST request to my EmployeeDetails API that will add a new Employee to the database. I will send a POJO of the employee in the request body. This is what the code looks like in the test class:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.restassured.http.ContentType;
import org.junit.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

public class EmployeeTests {

    @Test
    public void createEmployee() {

        // Create an object of POJO class
        EmployeeDetails emp = new EmployeeDetails();
        emp.setName("Vibha");
        emp.setSalary(75000);
        emp.setAge(30);

        // Converting a Java class object to a JSON payload as string
        ObjectMapper mapper = new ObjectMapper();
        String employeePrettyJson = null;
        try {
            employeePrettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        System.out.println("Request");
        System.out.println(employeePrettyJson);
        System.out.println("=========================================");
        System.out.println("Response");

        // GIVEN
        given().baseUri("https://dummy.restapiexample.com/api").contentType(ContentType.JSON).body(emp)

                // WHEN
                .when().post("/v1/create")

                // THEN
                .then().assertThat().statusCode(200).body("data.name", equalTo("Vibha"))
                .body("message", equalTo("Successfully! Record has been added.")).log().body();

    }

}

The output of the above program is

If you want to see the structure of the Request, then add the below in the test code.

ObjectMapper mapper = new ObjectMapper();
String employeePrettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp);
System.out.println(employeePrettyJson);

REST Assured Serialization with Jackson handled all the serialization work for us. Great! See, this has become so simple with the help of Jackson API.

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

How to test POST request from JSON Object in Rest Assured

HOME

In the last tutorial, I explained How to test POST Request using Rest Assured where the request body is in String Format. In this tutorial, I will create a request body using JSON Object in Rest Assured. This request body can be used for POST or PUT operations.

First, set up a basic Rest Assured Maven Project by clicking here and a Gradle project by clicking here.

In the previous post, you must have observed that I had hard-coded the JSON request body in a string format. It is not a good practice if you have a dynamic payload or want to create a payload at run time or parameterized one. It is always recommended to create a payload in a way that is easy to maintain. You should manage, update, and retrieve value from it easily. This can be achieved by JSONObject or JSONArray.

JSONObject is an unordered collection of key and value pairs, resembling Java’s native Map implementations. JSON stores data as a key-value pair. The key is the left side and the value is the right side, and a semicolon is used to separate both. One key-value pair is separated from another key-value pair using a comma (,).

The internal form is an object having the get and opt methods for accessing the values by name and put methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or JSONObject.NULL object.

To create a request body using JSON Object, we need to add a Maven dependency.

<dependencies>

    <dependency>
      <groupId>org.json</groupId>
      <artifactId>json</artifactId>
      <version>20240303</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>io.rest-assured</groupId>
      <artifactId>rest-assured</artifactId>
      <version>5.5.0</version>
      <scope>test</scope>
    </dependency>

 </dependencies>

JSONObject is imported from package:-

import org.json.JSONObject;

JSONObject exposes an API similar to Java’s Map interface. Below is an example of creating a request from a JSON Object. Here, Id is the auto-generated attribute. We are using the put() method and supply the key and value as an argument. I am using a logger just to print the JSON body in the Console. 

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.json.JSONObject;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;

public class Json_Demo {

    @Test
    public void passBodyAsJsonObject() {

        JSONObject data = new JSONObject();

        data.put("employee_name", "MapTest");
        data.put("profile_image", "test.png");
        data.put("employee_age", "30");
        data.put("employee_salary", "11111");

        RestAssured
                .given()
                .contentType(ContentType.JSON)
                .body(data.toString())
                .log().all()

                .when()
                .post("https://dummy.restapiexample.com/api/v1/create")

                .then()
                .assertThat().statusCode(200)
                .body("data.employee_name", equalTo("MapTest"))
                .body("data.employee_age", equalTo("30"))
                .body("data.employee_salary", equalTo("11111"))
                .body("data.profile_image", equalTo("test.png"))
                .body("message", equalTo("Successfully! Record has been added."))
                .log().all();

    }
}

The request body will look as shown below:-

The texts produced by the toString() methods strictly conform to the JSON syntax rules.

 .body(data.toString())

The above one is a simple JSON Request Body. Let’s take an example of a Complex Request Body or nested Request Body.

We need to create two JSONObject here. One will hold overall key-value pairs, and another JSONObject will hold only employee_details key-value pairs. 

Below is an example that shows how to create a complex JSON request body using JSONObject.

@Test
public void passBodyAsJsonObjectDemo() {
        
   //First JSONObject
	JSONObject data = new JSONObject();

	data.put("profile_image", "test.png");
        
    //Second JSONObject
	JSONObject detail = new JSONObject();

	detail.put("updated_message", "Details of New Resource");
	detail.put("employee_age", "30");

	data.put("employee_details", detail);

	data.put("employee_name", "MapTest");
	data.put("employee_salary", "11111");
	
	RestAssured
        .given()
               .contentType(ContentType.JSON)
               .body(data.toString())
               .log().all()
				
		.when()
              .post("http://dummy.restapiexample.com/api/v1/create")
				
		.then()
               .assertThat().statusCode(200)
               .body("data.employee_name", equalTo("MapTest"))
			   .body("data.employee_details.employee_age", equalTo("30"))
			   .body("data.employee_details.updated_message", equalTo("Details of New Resource"))
			   .body("data.employee_salary", equalTo("11111")).body("data.profile_image", equalTo("test.png"))
				.body("message", equalTo("Successfully! Record has been added."))
                .log().all();
	}
}

The request body will look as shown below:-

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