You can get the size of the JSON array using the size() method. Consider in below example you want to retrieve no of users in data array. Data array has 6 elements. So, size of array should return 6.
REST Endpoint: https://reqres.in/api/users?page=2
JSON Response
{
"page": 2,
"per_page": 6,
"total": 12,
"total_pages": 2,
"data": [
{
"id": 7,
"email": "michael.lawson@reqres.in",
"first_name": "Michael",
"last_name": "Lawson",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/follettkyle/128.jpg"
},
{
"id": 8,
"email": "lindsay.ferguson@reqres.in",
"first_name": "Lindsay",
"last_name": "Ferguson",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/araa3185/128.jpg"
},
{
"id": 9,
"email": "tobias.funke@reqres.in",
"first_name": "Tobias",
"last_name": "Funke",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/vivekprvr/128.jpg"
},
{
"id": 10,
"email": "byron.fields@reqres.in",
"first_name": "Byron",
"last_name": "Fields",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/russoedu/128.jpg"
},
{
"id": 11,
"email": "george.edwards@reqres.in",
"first_name": "George",
"last_name": "Edwards",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/mrmoiree/128.jpg"
},
{
"id": 12,
"email": "rachel.howell@reqres.in",
"first_name": "Rachel",
"last_name": "Howell",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/hebertialmeida/128.jpg"
}
],
"ad": {
"company": "StatusCode Weekly",
"url": "http://statuscode.org/",
"text": "A weekly newsletter focusing on software development, infrastructure, the server, performance, and the stack end of things."
}
}
Rest Assured JsonPath Array
public class ReqRes
{
@BeforeClass
public void setup()
{
RestAssured.baseURI = "https://reqres.in/";
RestAssured.basePath = "api";
}
@Test(enabled=true)
public void jsonArraySize()
{
// Obtain response from GET Request
Response res =
given()
.queryParam("page", "2")
.when()
.get("/users/");
// convert JSON to string
JsonPath js = new JsonPath(res.asString());
//getInt() will Get the result of an Object path expression as an int.
// size() will get the size of data array
int size = js.getInt("data.size()");
System.out.println("Size of the array is:"+size);
}
}
- Log in to post comments