How to create JSON Array Request Body

HOME

In the last tutorial, I explained  How to test POST JSON Object request using Java Map in Rest Assured . In this tutorial, I will create a request body using JSON Array in Rest Assured. This request body can be used for POST or PUT operations.

What is JSONArray?

JSONArray represents an immutable JSON array (an ordered sequence of zero or more values). It also provides an unmodifiable list view of the values in the array.

  1. JSON array can store multiple value types. The values in a JSONArray can be of the following types: JsonObject, JsonArray, JsonString, JsonNumber, JsonValue.TRUE, JsonValue.FALSE, and JsonValue.NULL.
  2. The array index begins with 0.
  3. The square brackets [ ] are used to declare the JSON array.

An API may accept a JSON Array payload as a request body. Imagine, we want to add employee details of more than one employee in the below example. In this case, we can pass multiple JSON objects within a JSON array. I have explained 2 ways to create JSON Object – map or JsonObject. Refer to any one of the tutorials to get to know about the creation of JSON Object.

To create a JSON Array, we need to add a Maven dependency, as shown below.

<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20210307</version>
</dependency>  

JSONObject is imported from the package:

import org.json.JSONObject;

JSONArray is imported from package:

import org.json.JSONArray;

Below is an example of JSONArray.

How to create JSONArray Request Body or payload?

  1. Create a JSON Object and add the first employee details.
  2. Create another JSON Object and add second guest details
  3. Create a JSONArray.
  4. Add both JSON Objects to JSONArray.

Below is an example of creating a request from JSONArray with multiple JSON Objects.  I am using a logger just to print the JSON body in the Console. 

public class RequestBodyAsJSONArrayDemo {

	@Test
	public void passBodyAsJsonArrayDemo() {

		// JSON Object for first employee
		JSONObject data1 = new JSONObject();

		data1.put("employee_name", "ObjectTest");
		data1.put("profile_image", "test1.png");
		data1.put("employee_age", "30");
		data1.put("employee_salary", "11111");

		// JSON Object for second employee
		JSONObject data2 = new JSONObject();

		data2.put("employee_name", "MapTest");
		data2.put("profile_image", "test2.png");
		data2.put("employee_age", "20");
		data2.put("employee_salary", "99999");

		// Creating JSON array to add both JSON objects
		JSONArray array = new JSONArray();
		array.put(data1);
		array.put(data2);

		// Send the request		
        RestAssured.given()
                          .contentType(ContentType.JSON)
                          .body(array.toString())
                          .log().all()
				
				.when()
                       .post("http://dummy.restapiexample.com/api/v1/create")
				
				.then()
                      .assertThat().statusCode(200)
                      .body("message", equalTo("Successfully! Record has been added."))
				      .log().all();
	}
}

Below is the execution screenshot.

Complex JSON Array

Let us see an example of a complex JSON Array.

{
    "employee1": [
      {
        "firstname": "Tom",
        "salary": 720000,
        "age": 59,
        "lastname": "Mathew"
     }
    ],
    "employee2": [
     {
        "firstname": "Perry",
        "salary": 365000,
        "age": 32,
        "lastname": "David"
    }
   ]
}

This JSON Array can be created as

    @Test
	public void passBodyAsJsonArray() {

		// JSON Object for first employee
		JSONObject data1 = new JSONObject();

		data1.put("firstname", "Tom");
		data1.put("lastname", "Mathew");
		data1.put("age", 59);
		data1.put("salary", 720000);

		// JSON Object for second employee
		JSONObject data2 = new JSONObject();

		data2.put("firstname", "Perry");
		data2.put("lastname", "David");
		data2.put("age", 32);
		data1.put("salary", 365000);

		// Creating first JSON array 
		JSONArray array1 = new JSONArray();
		array1.put(data1);

		// Creating second JSON array 
		JSONArray array2 = new JSONArray();
		array2.put(data2);

		// Create JSON Object to add both JSONArrays
		JSONObject data3 = new JSONObject();
		data3.put("employee1", array1);
		data3.put("employee2", array2);

		System.out.println(data3);

	}

Similarly, there is another way to create this JSON Structure.

    @Test
	public void passBodyAsJsonArray1() {

		// Creating JSON array to add first JSON object
		JSONArray array1 = new JSONArray();
		array1.put(new JSONObject().put("firstname", "Tom").put("lastname", "Mathew").put("age", 59).put("salary",
				720000));

		// Creating JSON array 
		JSONArray array2 = new JSONArray();
		array2.put(new JSONObject().put("firstname", "Perry").put("lastname", "David").put("age", 32).put("salary",
				365000));

		// Create JSON Object to add JSONArrays
		JSONObject data1 = new JSONObject();
		data1.put("employee1", array1);
		data1.put("employee2", array2);

		System.out.println(data1.toString(4));

	}
}

Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!

5 thoughts on “How to create JSON Array Request Body

  1. I want to POST an array in an Object like this is my baseURI: http://localhost:3000/FamousPersonalities
    and below is the JSON
    {
    “Males”: [
    {
    “firstname”: “Tom”,
    “lastname”: “Cruise”,
    “age”: 59
    }
    ],
    “FeMales”: [
    {
    “firstname”: “Lata”,
    “lastname”: “Mangeshkar”,
    “age”: 92
    }
    ]
    }

    How can I navigate to “Males” array through baseURI what should be the path so that I can add an object in it. Please suggest and guide me.

    Like

    1. Hi Rama.. if you are looking to create the JSON body as shown in the above msg, you can try this

      JSONArray array1 = new JSONArray();
      array1.put(new JSONObject().put(“firstname”, “Tom”).put(“lastname”, “Cruise”).put(“age”, 59));

      // Creating JSON array to add second JSON object
      JSONArray array2 = new JSONArray();
      array2.put(new JSONObject().put(“firstname”, “Lata”).put(“lastname”, “Mangeshkar”).put(“age”, 92));

      // Create JSON Object to add JSONArrays
      JSONObject data1 = new JSONObject();
      data1.put(“males”, array1);
      data1.put(“females”, array2);

      System.out.println(data1);

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s