我正在使用volley并实现json解析。我正在进行json解析并在列表视图中显示数据。我做了所有的事情(getter setter,singleton class,adapter等)但是在解析的时候我遇到了困难,如何解析
{
"result": [{
"id": "1",
"name": "Prabhat",
"email": "prabhat@gmail.com"
}, {
"id": "2",
"name": "Apurva",
"email": "apu@gmail.com"
}, {
"id": "3",
"name": "sunny",
"email": "sunny@mail.com"
}, {
"id": "4",
"name": "Creation InfoTech",
"email": "creation@gmail.com"
}, {
"id": "5",
"name": "Sanjay Mishra",
"email": "sanju19@gmail.com"
}]
}
我的java代码是
JsonObjectRequest request = new JsonObjectRequest(url_Array, new JSONObject(), new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
for (int i = 0; i < response.length(); i++) {
try {
Log.d(TAG, "working");
JSONObject object = response.getJSONObject(i);
// Now this is my PersonInfo class in which i have define my getters and setters
PersonInfo info = new PersonInfo(object.getString("id"), object.getString("name"), object.getString("email"));
personInfos.add(info);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Something not ok", Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance(getApplicationContext()).AddtoRequestQueue(request);
}
**面对解析困难,请回复**
答案 0 :(得分:1)
在走完列表之前,首先需要获得JSONArray
:
JSONArray array = response.getJSONArray("result")
然后你走了数组:
for (int i = 0; i < array.length(); i++) {...}
答案 1 :(得分:0)
尝试此代码将帮助您将数据读入两个字符串数组,然后您可以随意使用它们
JsonObjectRequest request = new JsonObjectRequest(url_Array, new JSONObject(), new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
JSONArray jsonArray = jsnobject.getJSONArray("result");
String[] name=new String[jsonArray.length()];
String[] email=new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
try {
Log.d(TAG, "working");
JSONObject student=jsonArray.getJSONObject(i);
name[i]=student.getString("name");
email[i]=student.getString("email");
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Something not ok", Toast.LENGTH_SHORT).show();
}
}); AppController.getInstance(getApplicationContext()).AddtoRequestQueue(request);
}