REST Assured Tutorial 66 – How To Parse A JSON Array Response To A Java List In Rest Assured?

Introduction

As a part of the End to End REST Assured Tutorial, in this post, we will learn to parse a JSON Array response to a Java List 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 Array response into a Java List directly. It is useful if you do not use Pojo classes.

Prerequisite post

How To Parse A JSON Object Response To A Java Map In Rest Assured

Required Dependency

We are using the below version of Rest Assured:-



    io.rest-assured
    rest-assured
    4.3.3
    test

Parse JSON Array Response to Java List

Once a response is returned and if it is a JSON array then we can parse them as a List. There is a method called as() which takes a TypeRef reference to support classes with generics. For example – A JSON Array can be represented as a List<Object>. To cast Json Array 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.List;
import java.util.Map;

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

public class ParseJsonArrayResponseToList {

	public static void main(String[] args) {
		
		List> responseBody = null;
		
		responseBody = 
		RestAssured
			.given()
				.baseUri("https://restful-booker.herokuapp.com/")
				.basePath("booking")
			.when()
				.get()
			.then()
				.extract()
				.body()
				// Extract response as List>
				// Since the response in a List of Map format.
				.as(new TypeRef>>() {});
		
		System.out.println("Total bookings : "+ responseBody.size());
		
		System.out.println("All booking ids are: ");
		
		for(Map booking : responseBody)
		{
			System.out.println(booking.get("bookingid"));
		}
				
	}
}
Output
Total bookings : 10
All booking ids are: 
10
4
6
1
3
7
2
5
8
9

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.
#ThanksForReading
#HappyLearning

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 *