[英]How to find the length or size of the elements of response array in rest assured
我是 rest 的新手,放心。 我试过下面的代码来获得响应
RestAssured.baseURI = "http://localhost:8090/api";
Response resp =
given().
when().get("/modules")
.then().extract().response();
这是 JSON 响应
[
{
"moduleid": "1000",
"module": "reader",
"title": "Learn to read",
"description": "Learn to read and understand code"
},
{
"moduleid": "1005",
"module": "debug",
"title": "Can you fix it?",
"description": "Learn how to uncover logical mistakes"
},
]
如何获取该数组元素的长度或大小。
由于响应文档没有告诉您元素的数量(并且我们不确定服务器是否返回正确的content-size
header,因此您必须解析响应并计数。
你可以这样做:
public static void main(String[] args) {
RestAssured.baseURI = "http://demo1954881.mockable.io";
Response resp =
given().
when().get("/modules")
.then().extract().response();
ArrayList<Map> parsed = resp.jsonPath().get();
List<Map> result = parsed
.stream()
.filter(i -> "1000".equals(i.get("moduleid")))
.collect(Collectors.toList());
result.forEach(
map -> System
.out
.printf(
"Item with [moduleid=%s] has size of %d\n",
map.get("moduleid"), map.size())
);
}
由于您知道响应结构,因此它是一个简单的映射数组。 因此,您将其序列化为地图数组,然后使用常规工具集来处理数据。
如上评论,这里的length
是json object中键值对的个数。
对我来说,你可以选择数组中的任何 object 来计算键值对的数量,但是如果你想指定 json object 条件,例如moduleid=1005
你可以使用此代码
Map<String, Object> parsed = resp.jsonPath().get("find {it.moduleid = '1005'}");
int numberOfPair = parsed.keySet().size();
System.out.println(numberOfPair); //4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.