简体   繁体   中英

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

I am new to rest assured. 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

    [
        {
            "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.

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.

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.

Map<String, Object> parsed = resp.jsonPath().get("find {it.moduleid = '1005'}");
int numberOfPair = parsed.keySet().size();
System.out.println(numberOfPair); //4

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.

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