RestAssured #12 - Converting request payload to JSON using POJO with Serialization

RestAssured #12 - Converting request payload to JSON using POJO with Serialization

• What are serialization and deserialization? • What are JSON and its structure? • What is POJO in Java? • POJO representation for JSON payload

What are serialization and deserialization?

  • Serialization is translating a data structure or object state into a format that can be stored or transmitted and reconstructed later. The opposite operation, extracting a data structure from a series of bytes, is deserialisation.

  • ‎Why is serialization used? Application involving multiple platforms requires architecture independence. Serializing the data structure in an architecture-independent format means preventing the problems of byte ordering, memory layout, or simply different ways of representing data structures in different programming languages.

Why use serialization and deserialization in REST API automation?

To access the REST service, we have to transfer data between the client and the REST service. Using serialisation, an object having request details can be serialized into JSON/XML format which can be handled by REST service. And using deserialisation REST response which can be in JSON/XML format can be converted back to objects which be consumed by the client.

What are JSON and its structure?

JSON (JavaScript Object Notation) is a lightweight data-interchange format. JSON data is represented as key-value pairs, similar to a dictionary or a hash table.

Below are three components of JSON

  • JSON Object - A JSON object is an unordered collection of key-value pairs, where the keys are strings and the values can be any valid JSON data type enclosed in curly braces {}.

  • Key and values (JSON Data type)- The keys are always strings, followed by a colon, and the values can be any valid JSON data type such as strings, numbers, Boolean, arrays or objects.

  • JSON array - A JSON array is an ordered list of values enclosed in square brackets []

Here's an example of a JSON object that represents a person:

What is POJO in Java?

What is POJO (Plain Old Java Object) in Java?

POJO is a simple data structure that has private fields with a public getter and setter, but it does not have business implementation. It is used to improve the readability and reusability of a program.

‎POJO should not

  • ‎extend pre-specified class

  • ‎implement pre-specified interface

POJO should follow below the property

  • ‎class must be public

  • ‎instance variables must be private

  • ‎must have a public default constructor

  • ‎it should have a getter/setter method for accessing/updating instance variables

The code below is an example of POJO where the class represents a user object with a name, age, and email. The class has private fields that are accessed through public getters and setters. The default constructor takes no arguments, while the parameterized constructor takes values for all three fields. It has setter methods and getter methods for each field.

public class User {
    private String name;
    private int age;
    private String email;

    // Default constructor
    public User() {
    }

    // Constructor with parameters
    public User(String name, int age, String email) {
        this.name = name;
        this.age = age;
        this.email = email;
    }

    // Getters and setters
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

POJO representation for JSON payload

In this section will create POJO for below JSON -

{
    "name": "John Smith",
    "age": 35,
    "gender": "male",
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "CA",
        "zip": "12345"
    },
    "phoneNumbers": [
        {
            "type": "home",
            "number": "555-1234"
        },
        {
            "type": "work",
            "number": "555-5678"
        }
    ]
}

There are 3 types of values for the above JSON -

  • String or numbers - name, age and gender fields

  • JSON object - Address Class

  • JSON object array - PhoneNumber Class

First, we need to create a POJO class to represent the above JSON -

public class PersonPOJO {
    private String name;
    private int age;
    private String gender;
    private Address address;
    private List<PhoneNumber> phoneNumbers;

    public PersonPOJO(String name, int age, String gender, Address address, List<PhoneNumber> phoneNumbers) {
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.address = address;
        this.phoneNumbers = phoneNumbers;
    }

    public static class PhoneNumber{
        private String type;
        private String number;

        public PhoneNumber(String type, String number){
            this.type = type;
            this.number = number;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getNumber() {
            return number;
        }

        public void setNumber(String number) {
            this.number = number;
        }
    }

    public static class Address{
        private String street;
        private String city;
        private String state;
        private String zip;


        public Address(String street,String city,String state, String zip){
            this.street = street;
            this.city = city;
            this.state = state;
            this.zip = zip;
        }
        public String getStreet() {
            return street;
        }

        public void setStreet(String street) {
            this.street = street;
        }

        public String getCity() {
            return city;
        }

        public void setCity(String city) {
            this.city = city;
        }

        public String getState() {
            return state;
        }

        public void setState(String state) {
            this.state = state;
        }

        public String getZip() {
            return zip;
        }

        public void setZip(String zip) {
            this.zip = zip;
        }
    }

    public Address getAddress(){
        return this.address;
    }

    public void setAddress(Address address){
        this.address = address;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

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

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public List<PhoneNumber> getPhoneNumbers() {
        return phoneNumbers;
    }

    public void setPhoneNumbers(List<PhoneNumber> phoneNumbers) {
        this.phoneNumbers = phoneNumbers;
    }
}

To send a POST request with above payload using serialization, I am using localhost only to print request payload sent with request -

public class Person {
    PersonPOJO personPOJO;
    private final String baseUri = "https://localhost:7070";
    private final String dummyEndpointPath = "/auth/cookie/login/";

    public Person(String name, int age, String gender, PersonPOJO.Address address, List<PersonPOJO.PhoneNumber> phoneNumbers){
        RestAssured.baseURI = baseUri;
        personPOJO = new PersonPOJO(name,age,gender,address,phoneNumbers);
    }

    public void convertPOJOToJson(){
        RestAssured.given()
                .contentType(ContentType.JSON)
                .body(personPOJO)
                .log().body()
                .post(dummyEndpointPath);
    }
}

Below are test method to invoke convertPOJOToJson() method defined in Person class

public class PersonPOJOTest {
    Person person;

    @BeforeMethod
    public void setup(){
        PersonPOJO.Address myAddress = new PersonPOJO.Address("123 Main St","Anytown","CA","12345");
        PersonPOJO.PhoneNumber phoneNumber1 = new PersonPOJO.PhoneNumber("home","555-1234");
        PersonPOJO.PhoneNumber phoneNumber2 = new PersonPOJO.PhoneNumber("work","555-5678");
        List<PersonPOJO.PhoneNumber> phoneNumbers = new ArrayList<>();
        phoneNumbers.add(phoneNumber1);
        phoneNumbers.add(phoneNumber2);
        person = new Person("John Smith",35,"male",myAddress,phoneNumbers);
    }

    @Test
    public void convertPOJOToJsonTest(){
        person.convertPOJOToJson();
    }
}

Output

Git Hub Repo Link - https://github.com/sksingh329/RestAssuredTutorials

Did you find this article valuable?

Support SUBODH SINGH by becoming a sponsor. Any amount is appreciated!