1

how to retrieve values of the map returned by jsonPath().getMap methods of rest assured I am trying to get the response on below api in Map, which I am able to successfully get but when I try to access the value of key "id" in the below code, I get cast Error on line "String id = test.get("id");"

public void testRestAssured() {
        Response apiResponse = RestAssured.given().get("https://reqres.in/api/user/2");
        Map<String, String> test = apiResponse.jsonPath().getMap("data");
        System.out.println(test);
        String id = test.get("id");
        System.out.println("ID : " + id);
}

Error

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

I tried to do many things like

String id = test.get("id").toString();      
or
String id = String.valueOf(test.get("id"));

but nothing helped in resolution

api response is as follows

{
    "data": {
        "id": 2,
        "name": "fuchsia rose",
        "year": 2001,
        "color": "#C74375",
        "pantone_value": "17-2031"
    }
}
Akash Chavan
  • 325
  • 2
  • 7
  • 22

5 Answers5

2

Try the below code, it is working fine for me:

Response apiResponse = RestAssured.given().get("http://reqres.in/api/user/2");
Map<Object, Object> test = apiResponse.jsonPath().getMap("data");
System.out.println(test);
String id = test.get("id").toString();
System.out.println("ID : " + id);

The changes I have done is: change Map of (String, String) to Map (Object, Object) because we know that each key of map is string but value could be of any data type.

I hope it will solve your problem.

Saurabh
  • 301
  • 2
  • 3
0

Correct code is

    Response apiResponse = RestAssured.given().get("http://reqres.in/api/user/2");
    Map<Object, Object> test = apiResponse.jsonPath().getMap("data");
    System.out.println(test);

    for (Object e : test.keySet()) {
        System.out.println(" Key is " + e + "  , value is " + test.get(e));
Arun Nair
  • 425
  • 3
  • 11
0

simply try this:

import com.jayway.restassured.path.json.JsonPath;

JsonPath extractor = JsonPath.from(apiResponse.toString());
String id = extractor.getString("data.id");
Sudheer Singh
  • 555
  • 5
  • 10
0

You should define Object for map value. Because your json values are different types (String and int).

    // define Object type for map values

    Map<String, Object> test = apiResponse.jsonPath().getMap("data");
   
    // use casting for assigning

    int id = (int) test.get("id");
   
0

Do you really need to make from your response map object?

If not you can use this one:

String id = RestAssured.given().get("https://reqres.in/api/user/2")
             .then().extract().jsonPath().getString("data.id");
cheparsky
  • 514
  • 6
  • 20