我遇到了一个问题,需要检查嵌套JSON对象中是否存在某个键。我的嵌套JSON对象是指:父JSON对象中的一个键的值是一个JSON对象。因此,我需要检查这个键在整个JSON对象中是否存在。我得到的数据是一个String
对象。我知道可以将这个String
对象解析为JSON对象。
{
"claim_loss_type_cd": "TEL",
"claim_type": "002",
"claim_reason": "001",
"policy_number": "1234kk3366ff664",
"info": {
"ApplicationContext": {
"country": "US"
}
}
}
我曾使用containsKey()
方法来检查主JSON对象中的键是否存在,这个方法是有效的。但是对于检查像"info"这样的内部JSON对象,我需要再将该Object
解析为JSON对象,然后再次检查该键是否存在。
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
有没有更好的方法、API或者方法可以在不需要解析内部JSON对象的情况下检查内部JSON对象中是否存在,我正在使用Websphere应用服务器的原生IBM库com.ibm.json.java.JSONObject.JSONObject(),不使用额外的JSON解析器。
考虑上述JSON,例如"claim_type"是父JSON对象中的键,但"info"本身是一个JSON对象。所以我需要做的是检查完整的JSON中是否存在一个键,无论是在父级还是在任何子级JSON对象中,例如这里的"country"键。
编辑:感谢@chsdk,我找到了一种解决方案。如果有人使用其他API找到了任何解决方案,请回复,因为下面的解决方案将递归考虑进去,并且可能具有较大的空间/时间复杂度。
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;
}
\"country\"\s*:
进行匹配检查? - Adrian Shum