Finding the path in JSON maze.
We all know that api test automation trims down the time taken by automated validation of an application by lion share. But the challenge we face during the script development is how do we get the correct value from the api response. There could be multiple ways to unwind the response to reach your specific validation node and let’s discuss about few among those. Before we proceed, I assume you are a polyglot who understands Java as well.
e.g., 1: String value from JSON response.
First let’s consider a very simple response which a JSONObject with only keys & value (I meant, no child objects). You made the call to the api
String apiUrl = http://superherodirectory.com/getHeros/7003438919and the response you got is,
{
"firstName": "John",
"lastName": "Doe",
"roleId": "7003438919",
"emailId": "superman@hollywood.com",
"isAlive": "immortal"
}You won’t get easier response than this because, all you have is a JSONObject with the values in String format.
Assume, your intention is to validate the isAlive status.
Well, as it is very common to use RestAssured to make the api calls in automation projects, you would get a ‘response’ of type Response class. Now let’s make use of JSONObject in org.json library to convert this response into a JSONObject.
JSONObject responseObject = new JSONObject(response.asString());The major task is done. Using the desired key, we can get the corresponding value.
String isAlive = responseObject.get(“isAlive”).toString();Or we can make it even simpler:
String email = responseObject.getString(“isAlive”); Output will be “immortal” in both the cases.
e.g., 2: String value from inner object of a JSON response.
Here your response object is a bit more complex with inner objects and arrays of data.
{
"Email": {
"EmailAddress": "superman@hollywood.com",
"Status": [
{
"Name": "SMS",
"Opted": true
},
{
"Name": "Promotions",
"Opted": false
}
],
"Type": "Personal",
"TypeId": 1
},
"MemberSince": "2020-11-09",
"RoleID": "1012345678",
"RoleState": "Member",
"Status": "Active"
}We need to extract 2 different values from this. Email address & roleId.


