检查嵌套JSON中是否存在密钥 [英] Check whether a key exists or not in a nested JSON

查看:83
本文介绍了检查嵌套JSON中是否存在密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我陷入了需要检查嵌套JSON对象中是否存在密钥的情况.通过嵌套的JSON对象,我在父JSON对象中具有一个JSON对象作为其键之一的值.所以我需要检查此密钥是否存在于整个JSON对象中.我正在获取以下数据作为String对象.我知道我可以解析此String对象以获得JSON对象.

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"
    }
  }
}

我使用了containsKey()方法来检查主要JSON对象中密钥的存在,并且它可以工作.但是,要检查诸如"info"之类的任何内部JSON对象,我需要再次将该Object解析为JSON对象,然后再次检查密钥.

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

因此,有什么更好的方法,任何API或方法都可以检查任何内部JSON对象内部,而无需解析内部JSON对象.我正在为Websphere Application Server使用com.ibm.json.java.JSONObject.JSONObject()本机IBM库,并且没有正在使用的其他JSON解析器.

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.

考虑上述JSON,例如"claim_type"是父JSON对象中的键,而"info"本身是JSON对象. 因此,我需要做的是检查密钥是否存在于完整的JSON中,无论是在父级还是其子级JSON对象中的任何一个(例如此处的密钥"country")中.

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.

感谢@chsdk,我找到了解决方案.但是,如果其他人使用其他API来解决任何问题,请做出回应,因为以下解决方案将递归考虑在内&可能会有很大的时空复杂度.

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;
}

推荐答案

您可以使用 JSONObject 来解析您的json并使用其

You can use JSONObject to parse your json and use its has(String key) method to check wether a key exists in this Json or not:

 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()方法:

Or better you can simply check if the JSON String contains this key value, for example with 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

看看这种方法,它会在嵌套对象上进行迭代以检查密钥是否存在.

Take a look at this method, it iterates over the nested objects to check if the key exists.

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

这篇关于检查嵌套JSON中是否存在密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆