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


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.

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

      //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 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");
            System.out.println(zip);
            break;
         }
      }
   }
}

Output

Updated on: 17-Nov-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements