[英]Rest assured: Size of json 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);
}
这是json的回应
{"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}]}
如何计算id's or list
大小。 帮我。
您无需提取响应即可对此进行验证。 你可以这样做:
given().
header("authToken",userToken).
when().
get("/students").
then().
contentType(ContentType.JSON).
body("list.size()", is(5));
但是如果你想从响应中提取它,你也可以:
Response response =
given().
header("authToken",userToken).
when().
get("/students").
then().
contentType(ContentType.JSON).
extract().
response();
int sizeOfList = response.body().path("list.size()");
如果您只对列表的大小感兴趣,那么您可以这样做:
int sizeOfList =
given().
header("authToken",userToken).
when().
get("/students").
then().
contentType(ContentType.JSON).
extract().
path("list.size()");
如果只计算list
的大小,也许你可以:
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;
}
或正则表达式:
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"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.