[英]ClassCastException for downcast JSONObject to JSONArray
[英]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.