Search code examples
javarestrest-assuredrest-assured-jsonpath

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. I am not so fluent in Java, so that is why I need to know how to optimise the code.

Let's say I have an API, which output's JSON in this format -

{
   "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. I want to get the id of all the 400 records, and store in an array. 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?


Solution

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