Found answer for the below Request,
API request body,
[
{
"userId": "value1"
},{
"userId": "value2"
}
]
Solution :
public String sendingRequest(String uid, String uid1){
JSONObject user1 = new JSONObject();
user1.put("userId", uid);
JSONObject user2 = new JSONObject();
user2.put("userId", uid1);
JSONArray jsonArray = new JSONArray();
jsonArray.put(user1);
jsonArray.put(user2);
String jsonStr = jsonArray.toString();
System.out.println("jsonString: "+jsonStr);
return jsonStr;
}
Outcome:
[{"userId":"ljtdmm"},{"userId":"BBLSHl"}]
Answer from Madan Raj on Stack OverflowGitHub
github.com › rest-assured › rest-assured › issues › 805
(how to) Assert array on json response body contains element · Issue #805 · rest-assured/rest-assured
February 6, 2017 - I want to assert the roles array contains at least "ROLE_ADMIN". So I wrote this test: RestAssured.given(...).get(...) .then() .statusCode(200) .and() .body("roles", hasItem("ROLE_ADMIN"));
Author dialex
Top answer 1 of 2
1
Found answer for the below Request,
API request body,
[
{
"userId": "value1"
},{
"userId": "value2"
}
]
Solution :
public String sendingRequest(String uid, String uid1){
JSONObject user1 = new JSONObject();
user1.put("userId", uid);
JSONObject user2 = new JSONObject();
user2.put("userId", uid1);
JSONArray jsonArray = new JSONArray();
jsonArray.put(user1);
jsonArray.put(user2);
String jsonStr = jsonArray.toString();
System.out.println("jsonString: "+jsonStr);
return jsonStr;
}
Outcome:
[{"userId":"ljtdmm"},{"userId":"BBLSHl"}]
2 of 2
0
You can't do List<User>.class so try using ParameterizedTypeReference
Top answer 1 of 4
13
The body() method accepts a path and a Hamcrest matcher (see the javadocs).
So, you could do this:
response.then().assertThat().body("$", customMatcher);
For example:
// 'expected' is the serialised form of your Person
// this is a crude way of creating that serialised form
// you'll probably use whatever JSON de/serialisaiotn library is in use in your project
Map<String, Object> expected = new HashMap<String, Object>();
expected.put("id", 1);
expected.put("name", "text");
response.then().assertThat().body("$", Matchers.hasItem(expected));
2 of 4
12
This works for me:
body("path.to.array",
hasItem(
allOf(
hasEntry("firstName", "test"),
hasEntry("lastName", "test")
)
)
)
Make Selenium Easy
makeseleniumeasy.com › home › rest assured tutorial 24 – creating json array request body using list
REST Assured Tutorial 24 – Creating JSON Array Request Body Using List - Make Selenium Easy
February 19, 2025 - 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(
Naukri
naukri.com › code360 › library › rest-assured--creating-json-object-and-array-request-body
REST Assured – Creating JSON Object and Array Request ...
Almost there... just a few more seconds
TOOLSQA
toolsqa.com › rest-assured › read-json-response-body-using-rest-assured
How to Read Json Response Body using Rest Assured?
In the below code we will simply read the complete Response Body by using Response.getBody() and will print it out on the console window. @Test public void WeatherMessageBody() { RestAssured.baseURI = "https://restapi.demoqa.com/utilities/weather/city"; RequestSpecification httpRequest = RestAssured.given(); Response response = httpRequest.get("/Hyderabad"); // Retrieve the body of the Response ResponseBody body = response.getBody(); // By using the ResponseBody.asString() method, we can convert the body // into the string representation.
YouTube
youtube.com › rameshqaautomationplatform
RestAssured How to Validate Response Body Array Elements GET API PART4 AUG20220813 - YouTube
RestAssured How to Validate Response Body Array Elements GET API PART4How to fetch response body array object elements using rest assured conceptsblog link:h...
Published August 13, 2022 Views 368
Top answer 1 of 4
7
I dit it:
.body("validSession",is(true))
.body("description[0].userType", equalTo(1))
.body("description[0].userTypeDescription", containsString("xxx"))
.body("description[0].uname", containsString("xx"))
.body("description[0].distributorId", equalTo(1));
I tested and it worked. but I did not understand why it only worked by putting all elements of the array with index zero.
Can you explain?
2 of 4
0
Try using the following code snippet :
.body("description[0]", hasItem(1))
Let me know if it was helpful.
Google Groups
groups.google.com › g › rest-assured › c › Se_6IVpzepc
(how to) Check nested attribut inside an array attribut
April 30, 2018 - response.body("rows.owner", everyItem(is("myself"))); However I would much prefer do it using the matcher Matchers.hasProperty("owner") or even HasPropertyWithValue.hasProperty("owner", is("myself") Since for some other test, the value of the owner property is random and I just want to check the property is there and not null.
Stack Overflow
stackoverflow.com › questions › 74949665 › how-to-write-array-request-body-in-rest-assured
java - How to write array request body in rest assured - Stack Overflow
JSONObject jsonobj1 = new JSONObject(); jsonobj1.put("requestNumber", 749 ); jsonobj1.put("referenceNumber", "tyryrty"); jsonobj1.put("cardType", "aliqua pariatur enim cupidatat"); jsonobj1.put("companyName", "amet Lorem"); jsonobj1.put("contactEmail", "tempor dolor officia"); Map<String, Object> map= new HashMap<String,Object>(); map.put("serviceProviderEmailList", "ipsum nis"); List<Map<String, Object>> test=Arrays.asList(map); jsonobj1.put("serviceProviderEmailList", test); jsonobj1.put("approvedBy", "sup"); jsonobj1.put("approvedDate", "1962-07-15T01:00:55.437Z");
Top answer 1 of 8
82
Solved! I have solved it this way:
@Test
public void test() {
RestAssured.get("/foos").then().assertThat()
.body("size()", is(2));
}
2 of 8
15
You can simply call size() in your body path:
Like:
given()
.accept(ContentType.JSON)
.contentType(ContentType.JSON)
.auth().principal(createPrincipal())
.when()
.get("/api/foo")
.then()
.statusCode(OK.value())
.body("bar.size()", is(10))
.body("dar.size()", is(10));
Baeldung
baeldung.com › home › http client-side › getting and verifying response data with rest-assured
Getting and Verifying Response Data with REST-assured | Baeldung
October 26, 2025 - @Test public void givenMovie_whenMakingPostRequestToMovieEndpoint_thenCorrect() { Map<String, String> request = new HashMap<>(); request.put("id", "11"); request.put("name", "movie1"); request.put("synopsis", "summary1"); int movieId = given().contentType("application/json") .body(request) .when() .post(uri + "/movie") .then() .assertThat() .statusCode(HttpStatus.CREATED.value()) .extract() .path("id"); assertThat(movieId).isEqualTo(11); } Above, we first made the request object that we need to POST. We then extracted the id field from the returned JSON response using the path() method. We can also verify the response if it’s a JSON array:
Stack Overflow
stackoverflow.com › questions › 45646022 › restassured-response-validation-using-body-and-array-as-parameter
rest - RestAssured response validation using body and array as parameter - Stack Overflow
August 12, 2017 - I am trying to validate a REST response. Is it possible to use an array as parameter to containsonly? ... String values[] = line.split(","); given(). when(). then(). statusCode(200). body("value", containsOnly(values));
Google Groups
groups.google.com › g › rest-assured › c › UIt1VZQOe-Y
Validating an array within a collection
August 12, 2015 - It seems that it is as expected two arrays, but the matcher appears to think they're different I'm not quite sure why. Can anybody help? ... .body("categories", hasItems("Item->FirstItem, Item->SecondItem,Item->ThirdItem, Item->FourthItem, Item->FifthItem, Item->SixthItem", "Item->FirstItem"))
Google Groups
groups.google.com › g › rest-assured › c › HpgYDl_vu54
How to validate for "[]" empty array
given(). contentType("application/json; charset=utf-8"). body(requestFormat). expect().statusCode(200). when(). post(baseURl). then(). log().body(). assertThat().body("T", equalTo(1)). assertThat().body("A",equalTo("[]")); My tests always fails but I can't see any difference in the log · java.lang.AssertionError: JSON path A doesn't match. Expected: [] Actual: [] How do I check for empty array for a certain key ?