REST Assured Tutorial 65 – How to parse a JSON Object response to a Java Map in Rest Assured?


As a part of the End to End REST Assured Tutorial, in this post, we will learn to parse a JSON Object response to a Java Map in Rest Assured.

It is not always necessary to convert the response to a POJO class instance to fetch values. We can cast or convert a JSON Object response into a Java Map directly. It is useful if you do not use Pojo classes.

Required Dependency

We are using the below version of Rest Assured:-

Parse Json Object Response to Java Map

Once the response is returned and if it is a JSON object then we can parse them as a Map. There is a method called as() which takes a TypeRef reference to support classes with generics. For example – A JSON Object can be represented as a Map<String, Object>. To cast JSON Object response in such type we need to use as() method with TypeRef. TypeRef is an abstract class that is used to specify generic type information when de-serializing a response.

Example Program

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 responseBody = null;
		responseBody = 
				.body("{\r\n" + 
						"    \"firstname\" : \"Jim\",\r\n" + 
						"    \"lastname\" : \"Brown\",\r\n" + 
						"    \"totalprice\" : 111,\r\n" + 
						"    \"depositpaid\" : true,\r\n" + 
						"    \"bookingdates\" : {\r\n" + 
						"        \"checkin\" : \"2018-01-01\",\r\n" + 
						"        \"checkout\" : \"2019-01-01\"\r\n" + 
						"    },\r\n" + 
						"    \"additionalneeds\" : \"Breakfast\"\r\n" + 
				// Extract response as Map
				.as(new TypeRef>() {});
		// To print booking id
		System.out.println("Booking id is : "+responseBody.get("bookingid"));
		// If we do not use below annotation then also no problem. As we are directly casting without checking
		// so I have used it to surpass warning.
		// Since "booking" key holds another JSON Object to parsing it again as Map.
		Map bookingDetails = (Map)responseBody.get("booking");
		System.out.println("First name is "+ bookingDetails.get("firstname"));
Booking id is : 11
First name is Jim

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

You can subscribe to my YouTube channel RetargetCommon to learn from video tutorials.

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

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.

Leave a Reply

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