您可以使用 解析json并使用其 方法检查此Json中是否存在某个键:
String str="{\"claim_loss_type_cd\": \"TEL\",\"claim_type\":\"002\",\"claim_reason\": \"001\",\"policy_number\":\"1234kk3366ff664\",\"info\": {\"ApplicationContext\":{\"country\": \"US\"}}}";
Object obj=JSONValue.parse(str);
JSONObject json = (JSONObject) obj;
//Then use has method to check if this key exists or not
System.out.println(json.has("claim_type")); //Returns true
或者更好的是,您可以简单地检查JSON字符串是否包含此键值,例如使用indexOf()
method:
String str="{\"claim_loss_type_cd\": \"TEL\",\"claim_type\":\"002\",\"claim_reason\": \"001\",\"policy_number\":\"1234kk3366ff664\",\"info\": {\"ApplicationContext\":{\"country\": \"US\"}}}";
System.out.println(str.indexOf("claim_type")>-1); //Returns true
看一下此方法,它会在嵌套对象上进行迭代以检查键是否存在。
public boolean keyExists(JSONObject object, String searchedKey) {
boolean exists = object.has(searchedKey);
if(!exists) {
Iterator<?> keys = object.keys();
while( keys.hasNext() ) {
String key = (String)keys.next();
if ( object.get(key) instanceof JSONObject ) {
exists = keyExists(object.get(key), searchedKey);
}
}
}
return exists;
}
Object obj=JSONValue.parse(str);
JSONObject json = (JSONObject) obj;
System.out.println(keyExists(json, "country")); //Returns true