我最近开始使用 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.
关于java - 使用 Rest Assured 从 JSON 响应中获取所有 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54823821/