我正在http://json.org/javadoc/org/json/JSONObject.html上使用java类.
以下是我的代码片段.
String jsonResult = UtilMethods.getJSON(this.jsonURL, null);
json = new JSONObject(jsonResult);
Run Code Online (Sandbox Code Playgroud)
getJSON返回以下字符串
{"LabelData":{"slogan":"AWAKEN YOUR SENSES","jobsearch":"JOB SEARCH","contact":"CONTACT","video":"ENCHANTING BEACHSCAPES","createprofile":"CREATE PROFILE"}}
Run Code Online (Sandbox Code Playgroud)
现在......我如何获得'口号'的价值?
我尝试了页面上列出的所有方法,但没有一个工作.
phi*_*hag 130
String loudScreaming = json.getJSONObject("LabelData").getString("slogan");
Run Code Online (Sandbox Code Playgroud)
如果它是你所追求的更深的键/值,并且你没有处理每个级别的键/值数组,你可以递归搜索树:
public static String recurseKeys(JSONObject jObj, String findKey) throws JSONException {
String finalValue = "";
if (jObj == null) {
return "";
}
Iterator<String> keyItr = jObj.keys();
Map<String, String> map = new HashMap<>();
while(keyItr.hasNext()) {
String key = keyItr.next();
map.put(key, jObj.getString(key));
}
for (Map.Entry<String, String> 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;
}
Run Code Online (Sandbox Code Playgroud)
用法:
JSONObject jObj = new JSONObject(jsonString);
String extract = recurseKeys(jObj, "extract");
Run Code Online (Sandbox Code Playgroud)
使用/sf/answers/290468881/中的映射代码
| 归档时间: |
|
| 查看次数: |
239593 次 |
| 最近记录: |