【发布时间】:2015-02-16 10:17:10
【问题描述】:
如何解析片段 (listview) 中的复杂 json 数据。我不能将所有的 json 数据放在片段中。
错误
Json 数据
{
"users": [{
"userId": 1,
"name": "Dya Vega",
"profilePhoto": "https://graph.facebook.com/1301454197/picture?type=large",
"dateMatched": "1/1/2015",
"distance": "1 miles away",
"status": "Online",
"requestMessage": "Hi, can I know you?",
"like": 234,
"lastActive": "Active 1 hour ago"
}, {
"userId": 2,
"name": "Esa Ezzatinor",
"profilePhoto": "https://graph.facebook.com/1269334432/picture?type=large",
"dateMatched": "1/1/2015",
"distance": "2 miles away",
"status": "Online",
"requestMessage": "Hi, can I know you?",
"like": 234,
"lastActive": "Active 2 hour ago"
}]
}
HistoryFragment.java
public class HistoryFragment extends Fragment {
...
// Creating volley request obj
JsonArrayRequest userReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
User user = new User();
User.setName(obj.getString("name")); // error here
User.setThumbnailUrl(obj.getString("profilePicture")); // error here
User.setLastLogin(obj.getString("lastLogin")); // and here
// adding user to users array
userList.add(user);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
...
}
User.java(模型/对象)
public class User {
private String name, lastActive, profilePhotoUrl;
public User() {
}
public User(String name, String lastActive, String profilePhotoUrl) {
this.name = name;
this.lastActive = lastActive;
this.profilePhotoUrl = profilePhotoUrl;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastActive() {
return lastActive;
}
public void setLastActive(String lastActive) {
this.lastActive = lastActive;
}
public String getProfilePhotoUrl() {
return profilePhotoUrl;
}
public void setProfilePhotoUrl(String profilePhotoUrl) {
this.profilePhotoUrl = profilePhotoUrl;
}
}
【问题讨论】:
-
只在实例上调用 setter 而不是在类上,即在用户上不是 User ...它看起来像一个错字:)
-
添加到上面使用 GSON,这将轻松完成您的任务。
-
你在我的问题中检查我的模型:)
-
对不起,我的错误。用户假设是用户。该死的..
标签: java android json listview android-fragments