将JSONArray项转换为JSONObject - ClassCastException

时间:2015-09-07 10:12:18

标签: java json classcastexception org.json

我尝试在" org.json"的帮助下处理JSON响应。图书馆。所以,我将字符串响应转换为JSONArray:

JSONArray listWallPosts = jsonWallPosts.getJSONArray("response");

和listWallPosts包含例如这样的数据集:

[1388,
{
    "date": 1441127306,
    "from_id": 45700,
    "comments": {
        "count": 0,
        "can_post": 1
    },
    "to_id": 44970,
    "online": 0,
    "post_type": "post",
    "id": 2469,
    "text": "Some message",
    "reply_count": 0
},
{
    "date": 1425812975,
    "from_id": 16089771,
    "comments": {
        "count": 0,
        "can_post": 1
    },
    "to_id": 44970,
    "online": 0,
    "post_type": "post",
    "id": 2467,
    "text": "Some another message",
    "reply_count": 0,
}]

当我尝试循环处理列表项时:

for(int j=0; j< listWallPosts.length(); j++){
    JSONObject post = (JSONObject)listWallPosts.get(j);
    //do something
}

我面对 ClassCastException - java.lang.Integer无法强制转换为org.json.JSONObject

有人可以建议最好的方法来处理吗?我应该在try-catch中将转换从列表项包装到JSONObject还是有更好的选择?

2 个答案:

答案 0 :(得分:1)

您的回复看起来有某种ID以及与之关联的JSONObject列表。你可能需要像这样编码:

int id = listWallPosts.getInt(0);
for(int j = 1; j < listWallPosts.length(); j++) {
    JSONObject post = listWallPosts.getJSONObject(j);
}

答案 1 :(得分:0)

在我目前的方法中,我在 if 语句中使用 instanceof 处理它:

for(int j=0; j< listWallPosts.length(); j++){
    if(listWallPosts.get(j) instanceof JSONObject){
        JSONObject post = (JSONObject)listWallPosts.get(j);
        //to do something
    }
}
相关问题