How to get a JSON field in a nested JSON using Rest Assured?

Rest AssuredDynamic ProgrammingProgramming

We can get a JSON field in a complex nested JSON using Rest Assured. First, we shall obtain a Response body which is in JSON format from a request. Then convert it to string.

We shall send a GET request via Postman on a mock API URL and observe its Response.

Using Rest Assured, let us get the value of the Price field having the value as $150. It is part of the Items. We shall get the value of the Item Count field by traversing the path - Items.Price.

Example

Code Implementation

import static io.restassured.RestAssured.given;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
public class NewTest {
   @Test
   public void jsonValue() {

      //base URI with Rest Assured class
      RestAssured.baseURI = "https://run.mocky.io/v3";

      //obtain Response from GET request
      Response res = given()
      .when()
      .get("/8ec8f4f7-8e68-4f4b-ad18-4f0940d40bb7");

      //convert JSON to string
      JsonPath j = new JsonPath(res.asString());

      //get a field value from nested JSON
      String p = j.getString("Items.Price");
      System.out.println("Price is: " + p);
   }
}

Output

raja
Published on 17-Nov-2021 12:39:19
Advertisements