Android 如何从AsyncTask访问此Json?
我正在尝试从Json检索数据,如下所示:Android 如何从AsyncTask访问此Json?,android,json,android-asynctask,Android,Json,Android Asynctask,我正在尝试从Json检索数据,如下所示: { comments: [ { id: 78, comment_user_id: 81, comment_is_approve: 1, comment_ads_id: 373, comment_text: "commmmmmeeeent here ", created_at: "2017-03-19 08:32:17
{
comments: [
{
id: 78,
comment_user_id: 81,
comment_is_approve: 1,
comment_ads_id: 373,
comment_text: "commmmmmeeeent here ",
created_at: "2017-03-19 08:32:17",
updated_at: "2017-03-19 08:32:17",
user: {
id: 81,
first_name: "name",
last_name: "",
age: "",
email: "l@mail.com",
telephone: "234234234",
}
}
]
}
这是我的asyncTask()
:
List params=new ArrayList();
JSONObject json=jParser.makeHttpRequest(url+373,“GET”,参数);
//检查日志cat中的JSON响应
//Log.d(“所有注释:,json.toString());
试一试{
JSONArray comments=json.getJSONArray(“comments”);
//循环浏览所有评论
for(int i=0;ivalue
mapItems.put(“id”,id);
mapItems.put(“名字”,name);
mapItems.put(“注释文本”,注释文本);
mapItems.put(“电话”,phone);
联系人列表。添加(mapItems);
我可以获取commentText和id,但无法从用户数组中获取任何数据?
我应该向用户添加parantethes吗?或者如何实现这一点?您必须像这样应用嵌套结构
JSONArray arrUser1 = c.getJSONArray("user");
for (int j = 0; j < arrUser1.length(); j++) {
JSONObject c1 = arrUser1.getJSONObject(j);
name = c1.getString("first_name");
phone = c1.getString("telephone");
mapItems = new HashMap<>();
mapItems.put("id", id);
mapItems.put("first_name", name);
mapItems.put("comment_text", commentText);
mapItems.put("telephone", phone);
contactList.add(mapItems);
}
JSONArray arrUser1=c.getJSONArray(“用户”);
对于(int j=0;j
在这种情况下,用户是一个JSONObject。我不确定您为什么使用JSONArray
这应该足够了
JSONObject user = c.getJSONObject("user");
name = user.getString("first_name");
phone = user.getString("telephone");
这里的
user
不是数组。它是一个JsonObject
试试这个:
JSONObject User = c.getJSONObject("user");
String id = User.getString("id");
String first_name = User.getString("first_name");
或者修改json响应以返回数组
您的JSON响应也是无效的
这是有效的JSON响应:
{
"comments": [{
"id": 78,
"comment_user_id": 81,
"comment_is_approve": 1,
"comment_ads_id": 373,
"comment_text": "commmmmmeeeent here ",
"created_at": "2017-03-19 08:32:17",
"updated_at": "2017-03-19 08:32:17",
"user": {
"id": 81,
"first_name": "name",
"last_name": "",
"age": "",
"email": "l@mail.com",
"telephone": "234234234" //remove comma here
}
}]
}
你可以从中检查有效的JSON,我以前尝试过这个方法,但是
mapItems
无法到达第二个For循环中的字符串。你获取名称和电话值意味着检查你的HashMap初始化代码HashMap mapItems;
你不能定义JSONObject
和获取c.getJSONArray
这是非法的!你验证过JSON吗如果json是有效的,则t将起作用..您的用户对象包含一个额外的逗号..我想我在其他方面有问题,,,
{
"comments": [{
"id": 78,
"comment_user_id": 81,
"comment_is_approve": 1,
"comment_ads_id": 373,
"comment_text": "commmmmmeeeent here ",
"created_at": "2017-03-19 08:32:17",
"updated_at": "2017-03-19 08:32:17",
"user": {
"id": 81,
"first_name": "name",
"last_name": "",
"age": "",
"email": "l@mail.com",
"telephone": "234234234" //remove comma here
}
}]
}