java 检查嵌套 JSON 中是否存在键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31043606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:59:21  来源:igfitidea点击:

Check whether a key exists or not in a nested JSON

javajson

提问by Ankit Nigam

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 Stringobject. I know I can parse this Stringobject to get JSON object.

我陷入了需要检查嵌套 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"
    }
  }
}

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 Objectagain to JSON object and then check the key again.

我已经使用containsKey()方法来检查主 JSON 对象中的密钥是否存在并且它有效。但是为了检查像“信息”这样的任何内部 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

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 对象内部的 API 或方法,而无需解析内部 JSON 对象。我正在将com.ibm.json.java.JSONObject.JSONObject()本机 IBM 库用于 Websphere Application Server,并且我没有使用其他 JSON 解析器。

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.

考虑到上面的 JSON,就像“claim_type”是父 JSON 对象中的一个键,但“info”本身就是一个 JSON 对象。所以我需要做的是检查一个键是否存在于完整的 JSON 中,无论是在父对象中还是在它的任何子 JSON 对象中,例如这里的键“国家”。

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.

感谢@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;
}

采纳答案by cн?dk

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

你可以使用JSONObject来解析你的 json 并使用它的has(String key)方法来检查这个 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

EDIT:

编辑:

Or better you can simply check if the JSON String contains this key value, for example with indexOf()method:

或者更好的是,您可以简单地检查 JSON 字符串是否包含此键值,例如使用indexOf()方法:

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

EDIT 2:

编辑2:

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

回答by Zon

A ready-to-go method with correct casting of types:

具有正确类型转换的现成方法:

/**
 * JSONObject contains the given key. Search is also done in nested 
 * objects recursively.
 *
 * @param json JSONObject to serach in.
 * @param key Key name to search for.
 * @return Key is found.
 */
public static boolean hasKey(
  JSONObject json,
  String key) {

  boolean exists = json.has(key);
  Iterator<?> keys;
  String nextKey;

  if (!exists) {

    keys = json.keys();

    while (keys.hasNext()) {
      nextKey = (String) keys.next();

      try {
        if (json.get(nextKey) instanceof JSONObject) {
          exists =
            hasKey(
              json.getJSONObject(nextKey),
              key);
        }
      } catch (JSONException e) {
        e.printStackTrace();
      }
    }
  }

  return exists;
}

回答by RuWi89

Both solutions, which suggest to iterate the JsonObject recursively, have a little bug: they don't break the iteration when they finally find the searched key. So you have to break the while-loop, otherwise the loop will continue and if there is a next key, it will check this key and so on. The code example, which searches for the "country"-key only works, because 'country' is coincidentally the last key in its JsonObject.

这两种建议递归迭代 JsonObject 的解决方案都有一个小错误:当它们最终找到搜索到的键时,它们不会中断迭代。所以你必须打破while循环,否则循环将继续,如果有下一个键,它会检查这个键等等。搜索“国家/地区”键的代码示例仅有效,因为“国家/地区”恰好是其 JsonObject 中的最后一个键。

Example:

例子:

 /* ... */
    while (keys.hasNext()) {
          nextKey = (String) keys.next();

          try {
            if (json.get(nextKey) instanceof JSONObject) {
              exists = hasKey(json.getJSONObject(nextKey), key);

              if(exists){
                  break;
              }

            }
          } catch (JSONException e) {
            e.printStackTrace();
          }
        }
    /* ... */