How to read nested or complex responses in RestAssured response
- Dev Raj Sinha
- Jun 17, 2023
- 2 min read
To read nested responses in RestAssured, you can use JSONPath expressions or extract specific values by navigating through the nested JSON structure. RestAssured provides built-in support for JSONPath, making it easy to extract data from nested responses. Here's how you can read nested responses using RestAssured:
1. Import Required Classes:
First, import the necessary classes for RestAssured and JSONPath:
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
2. Send API Request and Get Response:
Send the API request using RestAssured and obtain the response. Make sure the response contains valid JSON data. Here's an example of sending a GET request and receiving the response:
Response response = RestAssured.get("https://api.example.com/endpoint");
In this example, we send a GET request to retrieve the response from `https://api.example.com/endpoint`, and the response is stored in the `response` variable.
3. Use JSONPath to Extract Nested Values:
With the response object in hand, you can use JSONPath expressions to extract nested values from the response. Here's an example:
JsonPath jsonPath = response.jsonPath();
String nestedValue = jsonPath.get("parentObject.childObject.nestedProperty");
In this example, we create a `JsonPath` object from the response using the `jsonPath()` method provided by RestAssured. The `get()` method is then used with a JSONPath expression to extract the nested value. You need to provide the complete path to the nested property, specifying each object level separated by dots.
You can also extract nested arrays or objects using JSONPath expressions. Here are a few examples:
- Extract an array of values from a nested array:
List<String> nestedArrayValues = jsonPath.getList("parentObject.childArray[*].property");
- Extract values from a nested object within an array:
String nestedObjectValue = jsonPath.get("parentArray[0].nestedObject.property");
In this example, we extract the value of the `property` within the `nestedObject` from the first element of the `parentArray`.
By utilizing JSONPath expressions and the `JsonPath` object provided by RestAssured, you can effectively navigate nested responses and extract specific values at different levels of the JSON structure. Make sure to specify the correct JSONPath expression to target the desired nested property or array element within the response.
Comments