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

Getting all ids from a JSON response using Rest Assured

我最近开始使用 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 个这样的对象。我想获取所有 400 条记录的 id,并存储在一个数组中。我可以这样做,但我认为该方法可以优化。

我当前的代码:

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

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

Response response 
// Code that assigns the response 

List<Long> idList = response.jsonPath().getList("records.id");
// Code that uses the id list.