我最近開始使用 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"));}如何最大限度地減少代碼行以實現相同的目標?
1 回答

一只斗牛犬
TA貢獻1784條經驗 獲得超2個贊
Response response
// Code that assigns the response
List<Long> idList = response.jsonPath().getList("records.id");
// Code that uses the id list.
添加回答
舉報
0/150
提交
取消