我使用Flicker API显示图片。我从包含数组的API获取JSON对象。但无法正确解析它。当我试图获取JSON数组时,它会出现异常:
类型org.json.JSONObject无法转换为JSONArray
以下是我的代码段。
JSONObject jsonObject = DataParser.getDataFromWeb();
try {
if (jsonObject != null) {
if (jsonObject.length() > 0) {
JSONArray array = null;
try {
array = jsonObject.getJSONArray("photos");
} catch (JSONException e) {
e.printStackTrace();
}
int lenArray = array.length();
if (lenArray > 0) {
for (int jIndex = 0; jIndex < lenArray; jIndex++) {
//my codes
}
}
}
} else {
}
} catch (JSONException je) {
Log.i(DataParser.TAG, "" + je.getLocalizedMessage());
}
我从请求中得到的回复如下:
{
"photos": {
"page": 1,
"pages": 100,
"perpage": 5,
"total": 500,
"photo": [
{
"id": "38935250244",
"owner": "130108065@N08",
"secret": "092b54d6be",
"server": "4740",
"farm": 5,
"title": "misty.morning.rise.up",
"ispublic": 1,
"isfriend": 0,
"isfamily": 0
},
{
"id": "27869878289",
"owner": "62440012@N04",
"secret": "5e9929c4b1",
"server": "4752",
"farm": 5,
"title": "Incoming",
"ispublic": 1,
"isfriend": 0,
"isfamily": 0
},
{
"id": "38942505174",
"owner": "45571539@N06",
"secret": "cbf3f74e37",
"server": "4741",
"farm": 5,
"title": "Golden-eye",
"ispublic": 1,
"isfriend": 0,
"isfamily": 0
},
{
"id": "39656469601",
"owner": "38945681@N07",
"secret": "b470e84c18",
"server": "4696",
"farm": 5,
"title": "New Year's Sunrise",
"ispublic": 1,
"isfriend": 0,
"isfamily": 0
},
{
"id": "25775783908",
"owner": "100250163@N03",
"secret": "a9dfe8ed85",
"server": "4742",
"farm": 5,
"title": "Dissipate",
"ispublic": 1,
"isfriend": 0,
"isfamily": 0
}
]
},
"stat": "ok"
}
答案 0 :(得分:1)
试试这个
JSONObject jsonObject = DataParser.getDataFromWeb();
try {
if (jsonObject != null) {
JSONObject phots= null;
try {
phots = jsonObject.getJSONObject("photos");
JSONArray array = null;
try {
array = phots.getJSONArray("photo");
int lenArray = array.length();
if (lenArray > 0) {
for (int jIndex = 0; jIndex < lenArray; jIndex++) {
//my codes
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}