将 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
}
}
我尝试在 "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
}
}