In this tutorial, we will convert a Java list into a JSON Object. Most of the times, the JSONs built in the organizations are complex. It contains string, int, list, arrays and soon.
In this tutorial, we will use the below mentioned dependency.
JSONArrayrepresents 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.
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.
The array index begins with 0.
The square brackets [ ] are used to declare the JSON array.
An API can 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 org.jsonMaven dependency, as shown below. The latest version can be found here.
Create a JSON Object and add the first employee details.
Create another JSON Object and add second guest details.
Create a JSONArray.
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.
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
public class Json_Demo {
@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("https://dummy.restapiexample.com/api/v1/create")
.then()
.assertThat().statusCode(200)
.body("message", equalTo("Successfully! Record has been added."))
.log().all();
}
}
The output of the above program is
Explanation:
1. Creating JSON Objects:
Two “JSONObject” instances (‘data1‘ and ‘data2‘) are created to represent two employees. Each JSON object contains employee details such as name, profile image, age, and salary.
// 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");
2. Creating a JSON Array:
A JSONArrayinstance is created, and both JSON objects (data1 and data2) are added to it.
JSONArray array = new JSONArray();
array.put(data1);
array.put(data2);
3. Sending the POST Request:
3.1 The RestAssured library constructs and sends the HTTP POST request. It sets the content type of the request to JSON.
contentType(ContentType.JSON)
3.2 Converts the JSON array into a string format and sets it as the body of the request.
.body(array.toString())
3.3 Logs all details of the request for debugging purposes.
4.2 Asserts that the response status code is 200, indicating a successful request.
.assertThat().statusCode(200)
4.3 Asserts that the body of the response contains the specified message, confirming successful addition of records.
.body("message", equalTo("Successfully! Record has been added."))
4.4 Logs all details of the response for debugging purposes.
.log().all()
Complex JSON Array
Let us see an example of a complex JSON Array. This structure represents two separate employee data sets. Each is contained within its own JSON array. The whole is encapsulated within a larger JSON object identified by keys employee1and employee2.
Two JSONArray instances (array1 and array2) are created to encapsulate each employee’s JSON object.
JSONArray array1 = new JSONArray();
array1.put(data1);
JSONArray array2 = new JSONArray();
array2.put(data2);
3. Composing The JSON Structure:
A third JSONObject, data3, is created to aggregate the two JSON arrays under separate keys: employee1 and employee2.
JSONObject data3 = new JSONObject();
data3.put("employee1", array1);
data3.put("employee2", array2);
4. Output the JSON Object:
The entire composite JSON structure (data3) is printed to the console. The toString(4) method formats the output with an indentation of 4 spaces for readability.
System.out.println(data3.toString(4));
Similarly, there is another way to create this JSON Structure.
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
public class Json_Demo {
@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));
}
}
The output of the above program is
Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!