I am new to rest assured. I have tried below code for getting response
@Test
public void getData() throws IOException {
Response response =
given().
header("authToken",userToken).
when().
get("/students").
then().
contentType(ContentType.JSON).
extract().
response();
String jsonStr = response.getBody().asString();
System.out.println("Tag List************************" + jsonStr);
}
This is json response
{"max":"20","list":[
{"id":1120,"sId":1120,"sIntId":"150","type":1},
{"id":1121,"sId":1121,"sIntId":"151","type":1}
{"id":1122,"sId":1122,"sIntId":"152","type":1}
{"id":1123,"sId":1123,"sIntId":"153","type":1}
{"id":1124,"sId":1124,"sIntId":"154","type":1}]}
How to calculate size of id's or list
. Help me.
You don't have to extract the response to validate this. You can just do like this:
given().
header("authToken",userToken).
when().
get("/students").
then().
contentType(ContentType.JSON).
body("list.size()", is(5));
But if you want to extract it from the response you can as well:
Response response =
given().
header("authToken",userToken).
when().
get("/students").
then().
contentType(ContentType.JSON).
extract().
response();
int sizeOfList = response.body().path("list.size()");
If you're only interested in the size of the list and nothing else you can do like this:
int sizeOfList =
given().
header("authToken",userToken).
when().
get("/students").
then().
contentType(ContentType.JSON).
extract().
path("list.size()");
if just count the size of list
, Maybe you can:
public static void main(String[] args) {
System.out.println(count(jsonStr, "\"id\""));
}
public static int count(String source, String sub) {
int count = 0;
for (int i = 0; (i = source.indexOf(sub, i)) != -1; i += sub.length()) {
++count;
}
return count;
}
Or Regex:
public static int countByRegex(String source, String pattern) {
Pattern p = Pattern.compile(pattern);
Matcher matcher = p.matcher(source);
int count = 0;
while(matcher.find())
count++;
return count;
}
System.out.println(countByRegex(str, "id"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.