[英]Parsing JSON result in android
嗨,我有以下JSON结果:
{
"returnCode": "1",
"result": [
{
"id": "109",
"account_id": "159",
"created_on": "2013-11-29 10:46:41",
"title": "iphone 5",
"currency_code": "USD",
"price": "500",
"is_owner": "0",
"photoCount": 1,
"commentList": [
{
"account_id": "159",
"created_on": "2013-11-29 10:46:41",
"name": "Jane Doe",
"comment": "Blah.. blah... blah..."
},
{
"id": "134",
"account_id": "144",
"created_on": "2013-12-04 16:21:49",
"name": "John Doe",
"comment": "Blah.. blah.. blah..."
}
],
"count_like": "1",
"count_dislike": "0",
"count_favorite": "0",
"count_comment": "1",
"is_order": "0"
}
]
}
这是我的代码:
public ArrayList<Comment> getComments(String jData) throws JSONException{
JSONObject jObj = new JSONObject(jData);
ArrayList<Comment> cList = new ArrayList<Comment>();
JSONArray jCommentArr = jObj.getJSONArray("commentList");
servResponse = (int) jObj.getInt("returnCode");
if(servResponse == 1){
for(int i=0; i<jCommentArr.length(); i++)
{
Comment comment = new Comment();
JSONObject jComment = jCommentArr.getJSONObject(i);
comment.commenterId = (int) jComment.getInt("account_id");
comment.commenterName = (String) jComment.getString("name");
comment.commentMessage = (String) jComment.getString("comment");
comment.postDate = (String) jComment.getString("created_on");
cList.add(comment);
}
}
return cList;
}
我只对JSON中的注释数组感兴趣(由“ commentList”标记指定。
但是,我的代码总是抛出JSON异常,表明cList包含空值。 谁能指出我的代码出错了怎么办?
谢谢
尝试这个..
JSONObject jObj = new JSONObject(jData);
ArrayList<Comment> cList = new ArrayList<Comment>();
servResponse = Integer.parseInt(jObj.getString("returnCode").trim());
JSONArray objarr = jObj.getJSONArray("result");
for(int i = 0;i< objarr.length();i++){
JSONObject jCment = objarr.getJSONObject(i);
if(servResponse == 1){
JSONArray jCommentArr = jCment.getJSONArray("commentList");
for(int j=0; j<jCommentArr.length(); j++)
{
Comment comment = new Comment();
JSONObject jComment = jCommentArr.getJSONObject(j);
comment.commenterId = Integer.parseInt(jComment.getString("account_id").trim());
comment.commenterName = jComment.getString("name").trim();
comment.commentMessage = jComment.getString("comment").trim();
comment.postDate = jComment.getString("created_on").trim();
cList.add(comment);
}
}
}
-> JSONArray jCommentArr = jObj.getJSONArray("commentList");
更改为-> JSONArray jCommentArr = jObj.getJSONArray("result");
干得好 :
JSONObject jObj = new JSONObject(jData);
ArrayList<Comment> cList = new ArrayList<Comment>();
JSONArray jTemp = jObj.getJSONArray("result");
JSONArray jCommentArr = jTemp.getJSONObject(0).getJSONArray("commentList");
这是因为您直接访问commentList,它是结果数组中包含的值。 您必须先访问它。
JSONArray commentList = jObj.getJSONArray("result").getJSONArray("commentList");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.