如果这是您需要的更深的键/值,并且您没有处理每个级别的键/值数组,则可以递归搜索树:
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);
}
Object value = jObj.get(key);
if (value instanceof JSONObject) {
finalValue = recurseKeys((JSONObject)value, findKey);
}
}
return finalValue;
}
用法:
JSONObject jObj = new JSONObject(jsonString);
String extract = recurseKeys(jObj, "extract");
使用来自https://stackoverflow.com/a/4149555/2301224的地图代码