- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
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 jsonAryValue() { //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()); //Zip for 2nd Location array String zip = j.getString("Location[1].zip"); System.out.println("Zip for 2nd Location array: " + zip); } }
Output
Advertisements