我最近開始使用 Rest Assured 測試一個(gè)新項(xiàng)目的 API。我對Java不是很流利,所以這就是為什么我需要知道如何優(yōu)化代碼。假設(shè)我有一個(gè) API,它以這種格式輸出 JSON -{ "records":[0: { "id" : 1232, "attribute1": "some_value", "attribute2": "some_value1"},1: { "id" : 1233, "attribute1": "some_new_value", "attribute2": "some_new_value1"}]}records陣列內(nèi)大約有 400 個(gè)這樣的對象。我想獲取id所有 400 條記錄中的一條,并將其存儲在一個(gè)數(shù)組中。我能夠這樣做,但我認(rèn)為可以優(yōu)化該方法。我當(dāng)前的代碼: 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"));}如何最大限度地減少代碼行以實(shí)現(xiàn)相同的目標(biāo)?
1 回答

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