Json Object - Getting the Key and the Value

后端 未结 3 1897
再見小時候
再見小時候 2021-01-07 15:44

I am a newbie to JSON . So If this is a very basic doubt don\'t scold me . I have a JSON Object Reference and I want to get the Key(Object has only one Key Value Pair) . How

相关标签:
3条回答
  • 2021-01-07 16:03

    Recursively search for a key, and if found, return its value

        String recurseKeys(JSONObject jObj, String findKey) throws JSONException {
    
        Iterator<?> keys = jObj.keys();
        String key = "";
    
        while (keys.hasNext() && !key.equalsIgnoreCase(findKey)) {
            key = (String) keys.next();
    
            if (key.equalsIgnoreCase(findKey)) {
                return jObj.getString(key);
            }
            if (jObj.get(key) instanceof JSONObject) {
                return recurseKeys((JSONObject)jObj.get(key), findKey);
            }
        }
    
        return "";
    }
    

    Usage:

    JSONObject jObj = new JSONObject(jsonString);
    String extract = recurseKeys(jObj, "extract");
    
    0 讨论(0)
  • 2021-01-07 16:07

    You can use jsonObject.keys() for getting all keys. Then you may iterate over keys to get the first key out of them like :

    Iterator<String> keys = jsonObject.keys();
    if( keys.hasNext() ){
       String key = (String)keys.next(); // First key in your json object
    }
    
    0 讨论(0)
  • 2021-01-07 16:22

    json.keys() will give all the keys in your JSONObject where json is an object of JSONObject

    0 讨论(0)
提交回复
热议问题