{
"204": {
"host": "https:\/\/abc.com\/production-source\/ChangSha\/2013\/12\/02\/0\/0\/A\/Content\/",
"timestamp": 1385909880,
"cover": ["17\/Pg017.png",
"18\/Pg018.png",
"1\/Pg001.png",
"2\/Pg002.png"],
"year": "2013",
"month": "12",
"day": "02",
"issue": "2013-12-02",
"id": "204"
},
"203": {
"host": "https:\/\/abc.com\/production-source\/ChangSha\/2013\/12\/01\/0\/0\/A\/Content\/",
"timestamp": 1385806902,
"cover": ["1\/Pg001.png",
"2\/Pg002.png",
"3\/Pg003.png",
"4\/Pg004.png"],
"year": "2013",
"month": "12",
"day": "01",
"issue": "2013-12-01",
"id": "203"
},
"202": {
"host": "https:\/\/abc.com\/production-source\/ChangSha\/2013\/11\/30\/0\/0\/A\/Content\/",
"timestamp": 1385720451,
"cover": ["1\/Pg001.png",
"2\/Pg002.png",
"3\/Pg003.png",
"4\/Pg004.png"],
"year": "2013",
"month": "11",
"day": "30",
"issue": "2013-11-30",
"id": "202"
}
}
以上示例json数组,如何获得204,203和202?感谢
我试过了:
JSONArray issueArray = new JSONArray(jsonContent);
for (int j = 0; j < issueArray.length(); j++) {
JSONObject issue = issueArray.getJSONObject(j);
String _pubKey = issue.getString(0);
}
答案 0 :(得分:26)
以上示例json数组,如何获取204,203和202?
不,当前字符串是JSONObject
而不是JSONArray
。如果内部JSONObject键动态为:
JSONObject issueObj = new JSONObject(jsonContent);
Iterator iterator = issueObj.keys();
while(iterator.hasNext()){
String key = (String)iterator.next();
JSONObject issue = issueObj.getJSONObject(key);
// get id from issue
String _pubKey = issue.optString("id");
}
答案 1 :(得分:10)
K先生给出的答案也是对的,但您也可以使用 jsonObject names()方法。请找到示例代码
for(int i = 0; i<jsonobject.length(); i++){
Log.e(TAG, "Key = " + jsonobject.names().getString(i) + " value = " + jsonobject.get(jsonobject.names().getString(i)));
}
我希望dis会帮助你
答案 2 :(得分:8)
使用此方法动态迭代json
private void parseJson(JSONObject data) {
if (data != null) {
Iterator<String> it = data.keys();
while (it.hasNext()) {
String key = it.next();
try {
if (data.get(key) instanceof JSONArray) {
JSONArray arry = data.getJSONArray(key);
int size = arry.length();
for (int i = 0; i < size; i++) {
parseJson(arry.getJSONObject(i));
}
} else if (data.get(key) instanceof JSONObject) {
parseJson(data.getJSONObject(key));
} else {
System.out.println("" + key + " : " + data.optString(key));
}
} catch (Throwable e) {
System.out.println("" + key + " : " + data.optString(key));
e.printStackTrace();
}
}
}
}
答案 3 :(得分:-1)
在这里,您尝试获取JSONArray
,但在json响应中,它是JSONObject
。
使用以下代码。
JSONObject issueObject = new JSONObject(jsonContent);
String _pubKey = issueObject.getString(0);