I try to process JSON response with help of "org.json" library. So, I convert string response to JSONArray:
JSONArray listWallPosts = jsonWallPosts.getJSONArray("response");
and listWallPosts contains for example such data set:
[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,
}]
When I try to process list items in loop:
for(int j=0; j< listWallPosts.length(); j++){
JSONObject post = (JSONObject)listWallPosts.get(j);
//do something
}
I face with ClassCastException -- java.lang.Integer cannot be cast to org.json.JSONObject .
Can someone suggest best approach to handle it? Should I wrap casting from list item to JSONObject in try-catch or are there better options?
Looks like your response has some sort of ID
and a list of JSONObject
s associated with it. You may have to code somewhat like this:
int id = listWallPosts.getInt(0);
for(int j = 1; j < listWallPosts.length(); j++) {
JSONObject post = listWallPosts.getJSONObject(j);
}
In my current approach I handle it with instanceof in if statement:
for(int j=0; j< listWallPosts.length(); j++){
if(listWallPosts.get(j) instanceof JSONObject){
JSONObject post = (JSONObject)listWallPosts.get(j);
//to do something
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.