繁体   English   中英

将 JSONArray 项转换为 JSONObject - ClassCastException

[英]Cast JSONArray item to JSONObject - ClassCastException

我尝试在“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 还是有更好的选择?

看起来您的响应具有某种ID和与之关联的JSONObject列表。 您可能必须像这样编写代码:

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

在我目前的方法中,我在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
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM