# How to parse a JSON response and get a particular field from the response in Rest Assured?

Rest AssuredDynamic ProgrammingProgramming

We can parse a JSON response and get a particular field from Response in Rest Assured. This is done with the help of the JSONPath class. To parse a JSON response, we have to first convert the response into a string.

To obtain the response we need to use the methods - Response.body or Response.getBody. Both these methods are a part of the Response interface.

Once a Response is obtained it is converted to string with the help of the asString method. This method is a part of the ResponseBody interface. Then we shall obtain the JSON representation from the response body with the help of the jsonPath method.

We shall first send a GET request via Postman on a mock API URL and go through the response.

## Example

Using Rest Assured, we shall get the values of the Course, id and Price fields.

import org.testng.annotations.Test;
import static io.restassured.RestAssured.*;
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import io.restassured.response.ResponseBody;
import io.restassured.specification.RequestSpecification;
public class NewTest {
@Test
void responseExtract() {
//base URI with Rest Assured class
RestAssured.baseURI = "https://run.mocky.io/v3";
//input details
RequestSpecification h = RestAssured.given();
//get response
Response r = h.get("/e3f5da9c-6692-48c5-8dfe-9c3348cfd5c7");
//Response body
ResponseBody bdy = r.getBody();
//convert response body to string
String b = bdy.asString();
//JSON Representation from Response Body
JsonPath j = r.jsonPath();
//Get value of Location Key
String l = j.get("Course");
System.out.println("Course name: " + l);
String m = j.get("id");
System.out.println("Course Id: " + m);
String n = j.get("Price");
System.out.println("Course Price: " + n);
}
}

## Output

Updated on 17-Nov-2021 12:10:35