我如何解析片段(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(Model / Object)
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;
}
}
请指教。谢谢。
答案 0 :(得分:3)
与User
类一样,所有方法都是non-static
,但尝试使用类名访问所有方法(仅使用类名访问的静态方法)。
创建类对象以访问所有方法
User user = new User();
现在使用user
从User类访问所有getter / setter方法。
如果想要在不使用类名创建对象的情况下访问所有方法,那么请在User类中使用所有方法添加静态。
答案 1 :(得分:2)
您应该将methods
设置为用户类Object
,如
User user = new User();
user.setName(obj.getString("name"));
user.setThumbnailUrl(obj.getString("profilePicture"));
user.setLastLogin(obj.getString("lastLogin"));
只能通过创建该类的Object来访问所有User类方法。