[英]How to parse JSON in on response
我正在使用 volley 并实现 json 解析。 我正在做 json 解析并在列表视图中显示数据。 我已经完成了所有事情(getter setter、singleton 类、适配器等)但是在解析时我遇到了困难,如何解析
{
"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);
}
**遇到解析困难,请回复**
在遍历列表之前,您首先需要获取JSONArray
:
JSONArray array = response.getJSONArray("result")
然后你遍历数组:
for (int i = 0; i < array.length(); i++) {...}
试试这段代码将帮助您将数据读入两个字符串数组,然后您可以对它们做任何想做的事情
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.