簡體   English   中英

放心:json響應的大小

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

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