最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

java - Json Object - Getting the Key and the Value - Stack Overflow

programmeradmin1浏览0评论

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 do I get it in Java ?

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 do I get it in Java ?

Share Improve this question asked May 23, 2014 at 10:12 algo1algo1 1151 gold badge3 silver badges13 bronze badges 1
  • see if this helps stackoverflow./questions/16306271/… – Hawk Commented May 23, 2014 at 10:14
Add a ment  | 

3 Answers 3

Reset to default 5

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
}

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

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)

  1. 暂无评论