JSONObject - How to get a value ?

匿名 (未验证) 提交于 2019-12-03 08:54:24

问题:

i'm using a java class on http://json.org/javadoc/org/json/JSONObject.html.

The following is my code snippet.

String jsonResult = UtilMethods.getJSON(this.jsonURL, null); json = new JSONObject(jsonResult); 

getJSON returns the following string

{"LabelData":{"slogan":"AWAKEN YOUR SENSES","jobsearch":"JOB SEARCH","contact":"CONTACT","video":"ENCHANTING BEACHSCAPES","createprofile":"CREATE PROFILE"}} 

Now...how do I get the value of 'slogan' ?

I tried all the methods listed on the page, but none of them worked.

回答1:

String loudScreaming = json.getJSONObject("LabelData").getString("slogan"); 


回答2:

If it's a deeper key/value you're after and you're not dealing with arrays of keys/values at each level, you could recursively search the tree:

public static String recurseKeys(JSONObject jObj, String findKey) throws JSONException {     String finalValue = "";     if (jObj == null) {         return "";     }      Iterator keyItr = jObj.keys();     Map map = new HashMap();      while(keyItr.hasNext()) {         String key = keyItr.next();         map.put(key, jObj.getString(key));     }      for (Map.Entry e : (map).entrySet()) {         String key = e.getKey();         if (key.equalsIgnoreCase(findKey)) {             return jObj.getString(key);         }          // read value         Object value = jObj.get(key);          if (value instanceof JSONObject) {             finalValue = recurseKeys((JSONObject)value, findKey);         }     }      // key is not found     return finalValue; } 

Usage:

JSONObject jObj = new JSONObject(jsonString); String extract = recurseKeys(jObj, "extract"); 

Using Map code from https://stackoverflow.com/a/4149555/2301224



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!