[英]Getting all ids from a JSON response using Rest Assured
I have recently moved to test API's for a new project with Rest Assured. 最近,我与Rest Assured一起为一个新项目测试API。 I am not so fluent in Java, so that is why I need to know how to optimise the code.
我不太熟练使用Java,所以这就是为什么我需要知道如何优化代码的原因。
Let's say I have an API, which output's JSON in this format - 假设我有一个API,它以这种格式输出JSON-
{
"records":[
0: {
"id" : 1232,
"attribute1": "some_value",
"attribute2": "some_value1"
},
1: {
"id" : 1233,
"attribute1": "some_new_value",
"attribute2": "some_new_value1"
}]}
There are around 400 such objects coming inside the records
array. records
数组内部大约有400个这样的对象。 I want to get the id
of all the 400 records, and store in an array. 我想获取所有400条记录的
id
,并将其存储在数组中。 I am able to do so, but I think the approach can be optimised. 我能够这样做,但是我认为可以优化该方法。
My current code : 我当前的代码:
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"));
}
How can I minimize the lines of code to achieve the same thing? 如何最小化代码行以实现同一目标?
Response response
// Code that assigns the response
List<Long> idList = response.jsonPath().getList("records.id");
// Code that uses the id list.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.