我的 JSON 的结构是,
"posts":[
//Post 1.
{
"images":{
"small":{
"url": "http://..."
"width": 64
},
"large":{
"url": "http://..."
"width": 128
}
},
"caption":"..."
},
{
//Post 2
"images":{
"small":{
"url": "http://..."
"width": 64
},
"large":{
"url": "http://..."
"width": 128
}
},
"caption":"..."
}
]
我想以字符串的形式从每个帖子中获取,posts -> images -> large -> url。
这是我所做的:
JSONArray jsonarray = jsonobject.getJSONArray("posts");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
JSONArray innerArray1 = jsonobject.getJSONArray("images");
JSONArray innerArray2 = innerArray1.getJSONArray(0); //gets "large"
JSONArray innerArray3 = innerArray2.getJSONArray(1); //gets "url"
String finalString = innerArray3.toString();
}
我期望 finalString 中的“url”值,但它最终为空。
我做错了什么?
最佳答案
“images”、“small”、“large”是 JSONObjects(注意大括号),而不是 JSONArrays(方括号),您需要这样提取它们。
JSONArray jsonarray = jsonobject.getJSONArray("posts");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
JSONObject innerObject1 = jsonobject.getJSONObject("images");
JSONObject innerObject2 = innerObject1.getJSONObject("large"); //gets "large"
String finalString = innerObject2.getString("url");
}
关于android - 如何访问 JSON 对象中的嵌套数组 (Android),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30552793/