使用 Rest Assured 从 JSON 响应中获取所有 id

我最近开始使用 Rest Assured 测试一个新项目的 API。我对Java不是很流利,所以这就是为什么我需要知道如何优化代码。


假设我有一个 API,它以这种格式输出 JSON -


{

   "records":[

0: {

        "id" : 1232,

        "attribute1": "some_value",

        "attribute2": "some_value1"


},

1: {

         "id" : 1233,

        "attribute1": "some_new_value",

        "attribute2": "some_new_value1"


}]}

records阵列内大约有 400 个这样的对象。我想获取id所有 400 条记录中的一条,并将其存储在一个数组中。我能够这样做,但我认为可以优化该方法。


我当前的代码:


 private static Response response;

 Response r;

 JSONParser parser = new JSONParser();

 String resp = response.asString();

 JSONObject json =  (JSONObject) parser.parse(resp);

 JSONArray records= ((JSONArray)json.get("records"));


 ArrayList<Long> idlist = new ArrayList<Long>();

 for(int i=0;i<records.size();i++) {

    idlist.add((Long) ((JSONObject)records.get(i)).get("id"));

}

如何最大限度地减少代码行以实现相同的目标?


狐的传说
浏览 133回答 1
1回答

一只斗牛犬

Response response&nbsp;// Code that assigns the response&nbsp;List<Long> idList = response.jsonPath().getList("records.id");// Code that uses the id list.&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java