簡體   English   中英

如何找到rest中響應數組元素的長度或大小有保證

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM