I am struggling a little bit to get a JSON response from the API server in a readable format.
So here is the page I am currently using for exercises: https://reqres.in/ Position 4, GET LIST Resource
I am able to retrieve the data from the server in the JSON format which looks like:
{
"page": 1,
"per_page": 6,
"total": 12,
"total_pages": 2,
"data": [
{
"id": 1,
"name": "cerulean",
"year": 2000,
"color": "#98B2D1",
"pantone_value": "15-4020"
},
{
"id": 2,
"name": "fuchsia rose",
"year": 2001,
"color": "#C74375",
"pantone_value": "17-2031"
},
and so on. I am able to retrieve one object in the form of String:
[id:1, name:cerulean, year:2000, color:#98B2D1, pantone_value:15-4020]
I have 6 objects like that in an array, I am looping through the JSON response using:
System.out.println("Json Array count: " count);
for (int i = 0; i<count; i ){
String books = js.getString("data[" i "]");
System.out.println(books);
}
Is there an easy way to transcribe this data to the list of maps? I.e K: id, V: 1 and K: name, V: cerulean etc
I am a freshman if it comes for coding.
Here is my whole class:
String baseURI = RestAssured.baseURI = "https://reqres.in";
RequestSpecification rs = given().header("Content-Type","application/json");
Response response = rs.when().get("/api/unknown");
System.out.println(response.getStatusCode());
response.then().statusCode(200);
Assert.assertEquals(200, response.getStatusCode());
String resource = response.prettyPrint();
JsonPath js = new JsonPath(resource);
int count = js.getInt("data.size()");
System.out.println("Json Array count: " count);
for (int i = 0; i<count; i ){
String books = js.getString("data[" i "]");
System.out.println(books);
}
CodePudding user response:
Just use generic get
of JsonPath
in your case like:
public static void main(String[] args) throws URISyntaxException {
String baseURI = RestAssured.baseURI = "https://reqres.in";
RequestSpecification rs = given().header("Content-Type","application/json");
Response response = rs.when().get("/api/unknown");
List<Map> result = response.jsonPath().get("data");
for(Map map: result){
System.out.println(map);
}
}