REST Assured Tutorial 24 – Creating JSON Array Request Body Using List

As a part of End to End REST Assured Tutorial, in this post We will learn:- How to create a JSON Array Payload using List in Java.

In the last post, we have learned creating JSON Object using Map.

An API may accept a JSON Array payload as well. For example:- Booking for multiple passengers at once. In this case, we may need to pass multiple JSON objects within a JSON array. An example is below:-

[
    {
        "firstname": "Amod",
        "additionalneeds": "Breakfast",
        "bookingdates": {
            "checkin": "2021-08-01",
            "checkout": "2021-08-02"
        },
        "totalprice": 222,
        "depositpaid": true,
        "lastname": "Mahajan"
    },
    {
        "firstname": "Animesh",
        "additionalneeds": "Breakfast",
        "bookingdates": {
            "checkin": "2021-07-01",
            "checkout": "2021-07-01"
        },
        "totalprice": 111,
        "depositpaid": true,
        "lastname": "Prashant"
    }
]

I just twisted Restful Booking API for multiple bookings at once. We need to add as many JSON Objects containing guest details as required in a JSON Array. For example:- I want to do two bookings at once so added two booking details.

So how can we create such payload?

We already know how to create a JSON Object using Map. A JSON Array in Java can be created using List or Set. So we need to perform below steps to create payload as above:-

  1. Create a JSON Object and add the first guest details.
  2. Create another JSON Object and add second guest details
  3. Create a List or Set object.
  4. Add both JSON Object to List.
// JSON Object for first guest
Map bookingOne = new HashMap();
bookingOne.put("firstname", "Amod");
bookingOne.put("lastname", "Mahajan");
bookingOne.put("totalprice", 222);
bookingOne.put("depositpaid", true);
		
Map bookingDatesMapForAmod = new HashMap<>();
bookingDatesMapForAmod.put("checkin", "2021-08-01");
bookingDatesMapForAmod.put("checkout", "2021-08-02");
		
bookingOne.put("bookingdates", bookingDatesMapForAmod);
bookingOne.put("additionalneeds", "Breakfast");
		
// JSON Object for second guest
Map bookingTwo = new HashMap();
bookingTwo.put("firstname", "Animesh");
bookingTwo.put("lastname", "Prashant");
bookingTwo.put("totalprice", 111);
bookingTwo.put("depositpaid", true);
		
Map bookingDatesMapForAnimesh = new HashMap<>();
bookingDatesMapForAnimesh.put("checkin", "2021-07-01");
bookingDatesMapForAnimesh.put("checkout", "2021-07-01");
		
bookingTwo.put("bookingdates", bookingDatesMapForAnimesh);
bookingTwo.put("additionalneeds", "Breakfast");
		
// Creating JSON array to add both JSON objects
List> jsonArrayPayload = new ArrayList<>();
		
jsonArrayPayload.add(bookingOne);
jsonArrayPayload.add(bookingTwo);
		

As Booking API does not accept JSON Array payload, but to show as an example, I am just passing it. Because of invalid payload, it is giving internal server error. You can ignore that and focus on creating a JSON Array.

Example:-

package DifferentWaysOfPassingPayloadToRequest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.testng.annotations.Test;

import io.restassured.RestAssured;
import io.restassured.http.ContentType;

public class CreatingNestedJsonArray {
	
	@Test
	public void CreatingNestedJsonObjectTest()
	{
		
		// JSON Object for first guest
		Map bookingOne = new HashMap();
		bookingOne.put("firstname", "Amod");
		bookingOne.put("lastname", "Mahajan");
		bookingOne.put("totalprice", 222);
		bookingOne.put("depositpaid", true);
		
		Map bookingDatesMapForAmod = new HashMap<>();
		bookingDatesMapForAmod.put("checkin", "2021-08-01");
		bookingDatesMapForAmod.put("checkout", "2021-08-02");
		
		bookingOne.put("bookingdates", bookingDatesMapForAmod);
		bookingOne.put("additionalneeds", "Breakfast");
		
		// JSON Object for second guest
		Map bookingTwo = new HashMap();
		bookingTwo.put("firstname", "Animesh");
		bookingTwo.put("lastname", "Prashant");
		bookingTwo.put("totalprice", 111);
		bookingTwo.put("depositpaid", true);
		
		Map bookingDatesMapForAnimesh = new HashMap<>();
		bookingDatesMapForAnimesh.put("checkin", "2021-07-01");
		bookingDatesMapForAnimesh.put("checkout", "2021-07-01");
		
		bookingTwo.put("bookingdates", bookingDatesMapForAnimesh);
		bookingTwo.put("additionalneeds", "Breakfast");
		
		// Creating JSON array to add both JSON objects
		List> jsonArrayPayload = new ArrayList<>();
		
		jsonArrayPayload.add(bookingOne);
		jsonArrayPayload.add(bookingTwo);
		
		
		
		//GIVEN
		RestAssured
		   .given()
			  .baseUri("https://restful-booker.herokuapp.com/booking")
			  .contentType(ContentType.JSON)
			  .body(jsonArrayPayload)
			  .log()
			  .all()
		// WHEN
		   .when()
			   .post()
		// THEN
		   .then()
			   .assertThat()
			   // Asserting status code as 500 as it does not accept json array payload
			   .statusCode(500)
			   .log()
			   .all();
	}

}

You can see passing JSON Array body in the output below:-

[RemoteTestNG] detected TestNG version 7.0.0
Request method:	POST
Request URI:	https://restful-booker.herokuapp.com/booking
Proxy:			
Request params:	
Query params:	
Form params:	
Path params:	
Headers:		Accept=*/*
				Content-Type=application/json; charset=UTF-8
Cookies:		
Multiparts:		
Body:
[
    {
        "firstname": "Amod",
        "additionalneeds": "Breakfast",
        "bookingdates": {
            "checkin": "2021-08-01",
            "checkout": "2021-08-02"
        },
        "totalprice": 222,
        "depositpaid": true,
        "lastname": "Mahajan"
    },
    {
        "firstname": "Animesh",
        "additionalneeds": "Breakfast",
        "bookingdates": {
            "checkin": "2021-07-01",
            "checkout": "2021-07-01"
        },
        "totalprice": 111,
        "depositpaid": true,
        "lastname": "Prashant"
    }
]
HTTP/1.1 500 Internal Server Error
Server: Cowboy
Connection: keep-alive
X-Powered-By: Express
Content-Type: text/plain; charset=utf-8
Content-Length: 21
Etag: W/"15-/6VXivhc2MKdLfIkLcUE47K6aH0"
Date: Thu, 27 Feb 2020 17:21:58 GMT
Via: 1.1 vegur

Internal Server Error
PASSED: CreatingNestedJsonObjectTest

===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 0
===============================================


===============================================
Default suite
Total tests run: 1, Passes: 1, Failures: 0, Skips: 0
===============================================


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

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.

3 thoughts on “REST Assured Tutorial 24 – Creating JSON Array Request Body Using List

  1. Good to learn like this step by step considering a simple scenario (jsonObject – javamap(string,string) and then thinking about the complex scenario(json object inside json javamap(string,object) and now jsonArray(set<map(string,object) using sets

  2. How to create JSON Object when payload consists both Json Object and Array as well.
    for example if Payload is like this:-
    {
    “resourceType”: “Patient”,
    “id”: “1206675”,
    “meta”: {
    “versionId”: “1”,
    “lastUpdated”: “2020-06-16T07:41:31.812+00:00”,
    “source”: “#iGHDs0yQrKWhYsKX”
    },
    “text”: {
    “status”: “generated”,
    “div”: “Short VICTOR IdentifierCT6151″
    },
    “identifier”: [ {
    “type”: {
    “coding”: [ {
    “system”: “http://terminology.hl7.org/CodeSystem/v2-0203”,
    “code”: “MR”,
    “display”: “Medical Record Number”
    } ],
    “text”: “Medical Record Number”
    },
    “value”: “CT6151”
    }, {
    “type”: {
    “coding”: [ {
    “system”: “http://terminology.hl7.org/CodeSystem/v2-0203”,
    “code”: “NIIP”,
    “display”: “National Insurance Payor Identifier”
    } ],
    “text”: “National Insurance Payor Identifier”
    },
    “value”: “9800001468”
    } ],
    “name”: [ {
    “family”: “Victor”,
    “given”: [ “Short” ]
    } ],
    “gender”: “male”
    }

    1. Hi! Abhishek, you must put JSONObjects into JSONArray and put all into JSONObject
      example
      JSONObject requestParams1 = new JSONObject();
      requestParams1.put(“objectType”, “TravelerRequest”);
      JSONObject requestParams2 = new JSONObject();
      requestParams2.put(“objectType”, “PlaceOfVisit”);
      JSONArray arrData = new JSONArray();
      arrData.add(requestParams1);
      arrData.add(requestParams2);
      JSONObject requestParams4 = new JSONObject();
      requestParams4.put(“jsonFullData”, arrData);
      requestParams4.put(“lang”, “en”);
      output
      {
      “jsonFullData”:[{},{}],
      “lang”:”en”
      }

Leave a Reply

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