Explain how to extract value using JSONPath.

We can use JsonPath in Rest Assured to extract value. This is done with the help of the jsonPath method (which is a part of the JsonPath class). After that, we need to use the get method and pass the key that we want to obtain from the JSON Response.

We shall first send a GET request via Postman on an endpoint and observe the JSON response. Here, the keys are userId, id, title, and body.


Code Implementation

import org.testng.annotations.Test;
import static io.restassured.RestAssured.*;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
public class NewTest {
   void getValueJsonPath() {

      //base URL
      RestAssured.baseURI = "https://jsonplaceholder.typicode.com";
      RestAssured.basePath = "/posts";

      //obtain a response in JSON
      Response r = given().contentType(ContentType.JSON)

      //JsonPath class
      JsonPath p = r.jsonPath();

      //get JSON fields
      String u = p.getString("userId");
      String i = p.getString("id");
      String t = p.get("title");
      String b = p.get("body");
      System.out.println("User Id: " + u);
      System.out.println("Id: " + i);
      System.out.println("Title: " + t);
      System.out.println("Body: " + b);