放心:json响应的大小

时间:2015-08-24 12:34:50

标签: java json rest-assured

我是新来的放心。我试过以下代码来获得回复

@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的大小。帮助我。

2 个答案:

答案 0 :(得分:13)

您不必提取响应以验证此问题。你可以这样做:

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

答案 1 :(得分:0)

如果只计算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"));