I'm using rest-assured to test an API. I want to handle a scenario where a key might not exist
Given:
{
"shop":{
"shopId":1892929,
"name":"bobs shop",
"type":"grocery"
}
}
...in which type
key is sometimes not present, I am trying to handle as follows, using theJSONObject has
method: https://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)
//restassured code yields response, passed into a JSONObject
JSONObject jsonObj = new JSONObject(response);
if(jsonObj.has(jsonObj.getJSONObject("shop").getString("type"))){
logger.info("Shop type found as: " + jsonObj.getJSONObject("shop").getString("type"));
}
This code block always evaluates to false even when type
is present.
Where am I going wrong?
.getString("type")
returnsgrocery
in your case (developer.android.com/reference/org/json/…) andgrocery
is not a key injsonObj
.shop
andtype
are both keys. So I want to check iftype
exists, and if so, get its key