We can create a JSON Object using a Map in Java. You must note here that I am using the word “JSON Object”. A JSON Object is a key-value pair and can be easily created using a Java Map. A Map in Java also represents a collection of key-value pairs.
Start with a very simple JSON Object:
{
"username" : "admin",
"password" : "password123"
}
Observe above JSON Object. It contains two key-value pairs. “username” and “password” are two keys and “admin” and “password123” are its corresponding values.
Following the same, we need to create a Map and put the above key-value pairs as they ae\re. Since key and value both are string, we can create a generic Map. See the example below:-
Map<String,String> authPayload = new HashMap<String,String>();
authPayload.put("username", "admin");
authPayload.put("password", "password123");
Now you can directly pass above Map object to body() method which is overloaded to accept Object type.
Complete example:–
package DifferentWaysOfPassingPayloadToRequest;
import java.util.HashMap;
import java.util.Map;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
public class CreatingRequestBodyUsingMap {
@Test
public void passBodyAsMap()
{
Map<String,String> authPayload = new HashMap<String,String>();
authPayload.put("username", "admin");
authPayload.put("password", "password123");
//GIVEN
RestAssured
.given()
.baseUri("https://restful-booker.herokuapp.com/auth")
.contentType(ContentType.JSON)
.body(authPayload)
.log()
.all()
// WHEN
.when()
.post()
// THEN
.then()
.assertThat()
.statusCode(200)
.log()
.all();
}
}
I am using a logger just to show you the JSON body. Observe Output below. You will see the request body:-
[RemoteTestNG] detected TestNG version 7.0.0
Request method: POST
Request URI: https://restful-booker.herokuapp.com/auth
Proxy: <none>
Request params: <none>
Query params: <none>
Form params: <none>
Path params: <none>
Headers: Accept=*/*
Content-Type=application/json; charset=UTF-8
Cookies: <none>
Multiparts: <none>
Body:
{
"password": "password123",
"username": "admin"
}
HTTP/1.1 200 OK
Server: Cowboy
Connection: keep-alive
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 27
Etag: W/"1b-CfXCADRO41immbrDETUmLRPUeGo"
Date: Mon, 24 Feb 2020 16:45:31 GMT
Via: 1.1 vegur
{
"token": "3ce7cd012765c9f"
}
PASSED: passBodyAsMap
===============================================
Default test
Tests run: 1, Failures: 0, Skips: 0
===============================================
===============================================
Default suite
Total tests run: 1, Passes: 1, Failures: 0, Skips: 0
===============================================
Now see some complex example:-
Above we have seen a very basic JSON object body. Let’s learn little complex JSON Object request body.
{
"firstname" : "Jim",
"lastname" : "Brown",
"totalprice" : 111,
"depositpaid" : true,
"bookingdates" : {
"checkin" : "2018-01-01",
"checkout" : "2019-01-01"
},
"additionalneeds" : "Breakfast"
}
A key in JSON Object can hold another JSON Object as well. Unlike the above example where we created generic Map as Map<String, String>, in this, we need to create a generic map as Map<String, Object> to allow a key in Map to have a JSON Object as value.
We need to create two Maps here. One will hold overall key-value pairs and another Map will hold only bookingdates key-value pairs. Refer example below:-
Map<String,Object> jsonBodyUsingMap = new HashMap<String,Object>();
jsonBodyUsingMap.put("firstname", "Jim");
jsonBodyUsingMap.put("lastname", "Brown");
jsonBodyUsingMap.put("totalprice", 111);
jsonBodyUsingMap.put("depositpaid", true);
Map<String,String> bookingDatesMap = new HashMap<>();
bookingDatesMap.put("checkin", "2021-07-01");
bookingDatesMap.put("checkout", "2021-07-01");
jsonBodyUsingMap.put("bookingdates", bookingDatesMap);
jsonBodyUsingMap.put("additionalneeds", "Breakfast");
Complete Example Code:-
package DifferentWaysOfPassingPayloadToRequest;
import java.util.HashMap;
import java.util.Map;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
public class CreatingNestedJsonObject {
@Test
public void CreatingNestedJsonObjectTest()
{
Map<String,Object> jsonBodyUsingMap = new HashMap<String,Object>();
jsonBodyUsingMap.put("firstname", "Jim");
jsonBodyUsingMap.put("lastname", "Brown");
jsonBodyUsingMap.put("totalprice", 111);
jsonBodyUsingMap.put("depositpaid", true);
Map<String,String> bookingDatesMap = new HashMap<>();
bookingDatesMap.put("checkin", "2021-07-01");
bookingDatesMap.put("checkout", "2021-07-01");
jsonBodyUsingMap.put("bookingdates", bookingDatesMap);
jsonBodyUsingMap.put("additionalneeds", "Breakfast");
//GIVEN
RestAssured
.given()
.baseUri("https://restful-booker.herokuapp.com/booking")
.contentType(ContentType.JSON)
.body(jsonBodyUsingMap)
.log()
.all()
// WHEN
.when()
.post()
// THEN
.then()
.assertThat()
.statusCode(200)
.log()
.all();
}
}
Output:-
[RemoteTestNG] detected TestNG version 7.0.0
Request method: POST
Request URI: https://restful-booker.herokuapp.com/booking
Proxy: <none>
Request params: <none>
Query params: <none>
Form params: <none>
Path params: <none>
Headers: Accept=*/*
Content-Type=application/json; charset=UTF-8
Cookies: <none>
Multiparts: <none>
Body:
{
"firstname": "Jim",
"additionalneeds": "Breakfast",
"bookingdates": {
"checkin": "2021-07-01",
"checkout": "2021-07-01"
},
"totalprice": 111,
"depositpaid": true,
"lastname": "Brown"
}
HTTP/1.1 200 OK
Server: Cowboy
Connection: keep-alive
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 195
Etag: W/"c3-a1U4h04tkfvUYEkrOJJWIFOJZWA"
Date: Mon, 24 Feb 2020 16:44:48 GMT
Via: 1.1 vegur
{
"bookingid": 11,
"booking": {
"firstname": "Jim",
"lastname": "Brown",
"totalprice": 111,
"depositpaid": true,
"bookingdates": {
"checkin": "2021-07-01",
"checkout": "2021-07-01"
},
"additionalneeds": "Breakfast"
}
}
PASSED: CreatingNestedJsonObjectTest
===============================================
Default test
Tests run: 1, Failures: 0, Skips: 0
===============================================
===============================================
Default suite
Total tests run: 1, Passes: 1, Failures: 0, Skips: 0
===============================================