简体   繁体   English

如何找到rest中响应数组元素的长度或大小有保证

[英]How to find the length or size of the elements of response array in rest assured

I am new to rest assured.我是 rest 的新手,放心。 I have tried below code for getting response我试过下面的代码来获得响应

RestAssured.baseURI = "http://localhost:8090/api";
Response resp = 
          given().
          when().get("/modules")
         .then().extract().response();

This is JSON 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"
       },
    ]

How do I get the length or size of the elements of that array.如何获取该数组元素的长度或大小

Since the response document does not tell you the amount of elements (and we are not sure whether the server returns a correct content-size header, you will have to parse the response and count.由于响应文档没有告诉您元素的数量(并且我们不确定服务器是否返回正确的content-size header,因此您必须解析响应并计数。

You can do something like this:你可以这样做:

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())
    );
}

Since you are ware of the response structure it is a simple array of maps.由于您知道响应结构,因此它是一个简单的映射数组。 So you serialize it into array of maps and then use regular toolset for manipulating with data.因此,您将其序列化为地图数组,然后使用常规工具集来处理数据。

As above comment, the length here is the number of key-value pair in the json object.如上评论,这里的length是json object中键值对的个数。

For me, you can choose any object in the array to count the number of key-value pair, but if you want to specify the json object with condition, for example moduleid=1005 , this code would work for you.对我来说,你可以选择数组中的任何 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM