Ab123
Ab123

Reputation: 433

Rest Assured: extracting list of values from Json Response using java

I have a JSON Response and want to extract list of values from response for e.g all the values of id's present.

{
"page": 2,
"per_page": 3,
"total": 12,
"total_pages": 4,
"data": [
    {
        "id": 4,
        "first_name": "Eve",
        "last_name": "Holt",
        "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/marcoramires/128.jpg"
    },
    {
        "id": 5,
        "first_name": "Charles",
        "last_name": "Morris",
        "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/stephenmoon/128.jpg"
    },
    {
        "id": 6,
        "first_name": "Tracey",
        "last_name": "Ramos",
        "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/bigmancho/128.jpg"
    }
]
}

I have tried below code but not able to achieve but it is only printing first value of id i.e 4.

public class Get_Request {

public static void main(String[] args) {

    RestAssured.baseURI = "https://reqres.in/";

    Response res  = given()
      .param("page", "2")
    .when()
      .get("/api/users")
    .then()
      .assertThat()
      .contentType(ContentType.JSON)
      .and()
      .statusCode(200).extract().response();

    /*String data = res.jsonPath().getString("data[0].first_name");

    System.out.println(data);
    */

    List<HashMap<String,Object>> allids = res.jsonPath().getList("data");


    HashMap<String,Object> firstid = allids.get(0);

    Object a =  firstid.get("id");

    System.out.println(a);


    }
}

I am beginner in rest assured also i am not sure whether we can achieve the same. Any help would be appreciated. Thanks in advance.

Upvotes: 3

Views: 10558

Answers (3)

Umesh Kumar
Umesh Kumar

Reputation: 1397

You can use JsonPath wildcards to extracts data from response , which will save you from writing code everytime you have such requirement, use below JsonPath to extract list of Ids from your response :

$..id

Upvotes: 0

Ab123
Ab123

Reputation: 433

Below Code will find all the ids present in the Response and it will print the result like 4 5 6

List<Integer> ids = res.jsonPath().getList("data.id");

    for(Integer i:ids)
    {

        System.out.println(i);
    }

Upvotes: 2

bhusak
bhusak

Reputation: 1390

That can be done by changing your path to data.id

List<Integer> ids = res.jsonPath().getList("data.id");
Integer id = ids.get(0);

Upvotes: 1

Related Questions