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

We can get a JSON array field in a 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.

Finally, to obtain a particular array value, we shall use the array index followed by the field name. We shall send a GET request via Postman on a mock API, and observe the Response.

Using Rest Assured, let us get the value of the second zip field having the value as 49086. It is part of the second JSON in the Location array. We shall get the value of the second zip by traversing the path - Location[1].zip.


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 {
   public void jsonAryValue() {

      //base URI with Rest Assured class
      RestAssured.baseURI = "";

      //obtain Response from GET request
      Response res = given()

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

      //Zip for 2nd Location array
      String zip = j.getString("Location[1].zip");
      System.out.println("Zip for 2nd Location array: " + zip);


Updated on: 17-Nov-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started