private void jsonParse() {
String url = "http://127.0.0.1:8000/products/products/";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject o = jsonArray.getJSONObject(i);
int id = o.getInt("id");
String title = o.getString("title");
String description = o.getString("description");
String price = o.getString("price");
mTextViewResult.append(title + ", " + String.valueOf(id) + ", "+price +"," + description + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);}
This is my android code
[ {
"id": 1,
"title": "t-shirt",
"description": "this is a good t-shirt",
"price": "39.99"
},
{
"id": 2,
"title": "Jeans",
"description": "this is a jean",
"price": "89.99"}]
This is my json data
How can i fetch the json data which don't have a json array name. In my android i need to have json array name to parse the json data.But my django rest api produce json data without json array name.
答案 0 :(得分:0)
The response is a list of jsons. You need a JSONArrayRequest object to get the JSONArray
.
Example:
String url = "http://127.0.0.1:8000/products/products/";
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
try {
// `response` is the JSONArray that you need to iterate
for (int i = 0; i < response.length(); i++) {
JSONObject o = response.getJSONObject(i);
int id = o.getInt("id");
String title = o.getString("title");
String description = o.getString("description");
String price = o.getString("price");
mTextViewResult.append(title + ", " + String.valueOf(id) + ", "+price +"," + description + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});