Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Dependencies Required
3.
Parse JSON Object Response to a Java Map
4.
Frequently Asked Questions
4.1.
What does a JSON object mean?
4.2.
Are the Java map and hashmap the same?
4.3.
What does client-server architecture mean?
4.4.
How is JSON converted to strings?
4.5.
Why does JSON replace XML?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

How to parse a JSON Object and Array response to a Java Map in Rest Assured?

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

REST stands for REpresentation of State Transfer, and Rest assured is the Java library. It validates the response of your code in the dynamic languages to the Java domain. 

Most of the time, this response is converted to a POJO class, but do you know it’s not necessary? A JSON Object response can be cast or converted into a Java Map. If you do not use Pojo classes, it is helpful.

how to parse a json object and array response to a java map in rest assured

This article will discuss how to parse a JSON object and array response to a java map in rest assured. We will start by discussing the dependencies required to parse a JSON object response to a java map. Afterwards, we will discuss the theoretical aspect to parse a JSON object response to a java map. At last, we will discuss the program to parse a JSON object response to a java map.

So, without further ado, let’s get started!

Dependencies Required

To parse JSON object response to a java map. We need to add the below-given rest-assured dependencies to our maven project.

<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>4.4.0</version>
    <scope>test</scope>
</dependency>
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Parse JSON Object Response to a Java Map

After installing the required dependency, let’s look at the theoretical approach of what we will do to parse JSON object response to a java map. We can parse the response as a Map once it is determined whether it is a JSON object. A function called as() accepts a TypeRef reference to support classes with generics. 

parse a json object response to a java map

For instance, a Map<String, Object> can be used to represent a JSON object. Use the as() method and TypeRef to cast the JSON Object response into that type. When de-serializing a response, generic type information is specified using the abstract class TypeRef.

Let’s look at the following example to parse JSON object response to a java map:

Example:

package RestAssuredConcepts;

import java.util.Map;

import io.restassured.RestAssured;
import io.restassured.common.mapper.TypeRef;
import io.restassured.http.ContentType;

public class ParseJsonObjectResponseToMap {

    public static void main(String[] args) {

        Map <String, Object > responseBody = null;

        responseBody =
            RestAssured
            .given()
            .baseUri("https://restful-booker.herokuapp.com/")
            .basePath("booking")
            .contentType(ContentType.JSON)
            .body("{\r\n" +
                "    \"firstname\" : \"Jim\",\r\n" +
                "    \"lastname\" : \"Clarke\",\r\n" +
                "    \"totalprice\" : 5139,\r\n" +
                "    \"depositpaid\" : true,\r\n" +
                "    \"bookingdates\" : {\r\n" +
                "        \"checkin\" : \"2022-11-07\",\r\n" +
                "        \"checkout\" : \"2022-11-06\"\r\n" +
                "    },\r\n" +
                "    \"additionalneeds\" : \"Breakfast\"\r\n" +
                "}")
            .when()
            .post()
            .then()
            .extract()
            .body()
        // Extract response as Map<String,Object>
        .as(new TypeRef < Map < String, Object >> () {});

        // For printing the booking id
        System.out.println("Booking id is : " + responseBody.get("bookingid"));

        // If we do not want to use the below annotation then no problem, we can directly cast without checking

        @SuppressWarnings("unchecked")
        // Since "booking" key hold another JSON Object to parse again as Map.
        Map < String, Object > bookingDetail = (Map < String, Object > ) responseBody.get("booking");

        System.out.println("First name is " + bookingDetail.get("firstname"));

    }
}


Output: 

output

Explanation:

In the above example, we get a response in the form of a JSON object.  We used the JSONPath class and its methods to parse the JSON body and find the value of a certain attribute (booking id). For this, the function .as(new TypeRef<Map<String, Object>>() {}) accepts a TypeRef reference to support classes with generics (string and object). Afterwards, we send get request to ask for output from the response body.  

Must Read Array of Objects in Java

Frequently Asked Questions

What does a JSON object mean?

A JSON object is a collection of key-value pairs. The values are JSON types, while the keys are strings. A colon separates the keys and values. The key/value pair entries are separated by commas.

Are the Java map and hashmap the same?

While Java map is a Java interface used to map key-pair values, HashMap is a non-synchronized Java Collection Framework class with null values and keys.

What does client-server architecture mean?

A server provides resources and services to one or more clients using the client-server concept. A few examples include file servers, mail servers, and web servers. As a result, the server accepts the client's request.

How is JSON converted to strings?

For this, JSON.stringify() is employed. A string will be the outcome. It will adhere to JSON formatting.

Why does JSON replace XML?

JSON is made for exchanging data. It is, therefore, quicker than XML. Furthermore, a JavaScript function can parse JSON. XML, however, needs an XML parser.

Conclusion

This article briefly discussed how to parse a JSON object and array response to a java map in rest assured. We had discussed the dependencies required to parse a JSON object response to a java map. Afterwards, we discussed the theoretical aspect to parse a JSON object response to a java map. At last, we discussed the program to parse a JSON object response to a java map. Thus concluding our discussion on the topic of how to parse a JSON object response to a java map.

We hope this blog has helped you enhance your knowledge of parse a JSON object and array response to a java map in REST assured. If you like to learn more, you can check out our articles: 

 

Recommended problems -

 

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptAWS and many more! If you wish to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! 

If you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. For placement preparations, you must look at the problemsinterview experiences, and interview bundles.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Happy Learning!

Previous article
REST Assured – How to pass value from one API to Another API using TestNG – ITestContext
Next article
REST Assured – Compare Two JSON using Jackson – Java Library
Live masterclass