How to get JSON fields(nodes) based on conditions using Rest Assured?

Rest AssuredDynamic ProgrammingProgramming

We can get JSON fields(nodes) based on conditions using Rest Assured. First, we shall obtain a Response body which is in JSON format from a request. Then convert it to string.

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 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 zip field having the State value as New York.


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 jsonValueCondition() {

      //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());

      //get values of JSON array after getting array size
      int s = j.getInt("Location.size()");
      for(int i = 0; i < s; i++) {
         String state = j.getString("Location["+i+"].State");

         //check if condition meets
         if(state.equalsIgnoreCase("New York")) {
            String zip = j.getString("Location["+i+"].zip");


Updated on 17-Nov-2021 12:52:07