I am stuck in a situation where I need to check whether a key exists in a nested JSON object. By nested JSON Object that I am having a JSON object inside the parent JSON object as the value of one of its key. So i need to check whether this key exists in entire JSON object. I am getting the below data as a String
object. I know I can parse this String
object to get JSON object.
{
"claim_loss_type_cd": "TEL",
"claim_type": "002",
"claim_reason": "001",
"policy_number": "1234kk3366ff664",
"info": {
"ApplicationContext": {
"country": "US"
}
}
}
I have used containsKey()
method to check the key existence in the main JSON object and it works. But for checking any internal JSON object like "info" I need to parse that Object
again to JSON object and then check the key again.
String jsonString = "My JSON String here";
JSONObject finalResponse = new JSONObject(jsonString);
finalResponse.containsKey("country"); // will return false
JSONObject intermediateResponse = (JSONObject)finalResponse.get("info");
intermediateResponse.containsKey("country"); // will return true
So is there any better way, any API or method which can check inside any internal JSON object as well without the need of parsing the internal JSON object. I am using com.ibm.json.java.JSONObject.JSONObject()
native IBM library for Websphere Application Server and No additional JSON parsers I am using.
Considering the above JSON, like "claim_type" is a key in parent JSON object but "info" in itself a JSON object. So what i need to do is to check whether a key exists in complete JSON, either in parent or any of its child JSON object like key "country" here in example.
EDIT:
Thanks to @chsdk I came to a solution. But if anyone else came to any solution using some other API, please respond, because below solution is taking recursion into account & might have big Space/Time Complexity.
public static boolean checkKey(JSONObject object, String searchedKey) {
boolean exists = object.containsKey(searchedKey);
if(!exists) {
Set<String> keys = object.keySet();
for(String key : keys){
if ( object.get(key) instanceof JSONObject ) {
exists = checkKey((JSONObject)object.get(key), searchedKey);
}
}
}
return exists;
}
See Question&Answers more detail:os