长话短说我遇到这种问题,我试图向我的服务器发送凌空请求,该服务器以json数组响应:
{
"images": [{
"product_serial_num": "1",
"product_title": "Abbadon",
"product_img": "http://1.2.3.4/android/uploads/1.jpg",
"product_price": "750",
"product_description": "The destroyer"
}]
}
但无论我尝试了什么,我仍然会得到Volley的反应错误,我的截击请求:
requestQueue = Volley.newRequestQueue(getActivity());
//JsonArrayRequest of volley
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(MY_URL ,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
//parseData to parse the json response
parseData(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//If an error occurs that means end of the list has reached
Toast.makeText(getActivity(), "No More Items Available", Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(jsonArrayRequest);
奇怪的是,对于排球请求它确实有效,只有数组会让我感到困惑。
编辑:
这样我怎样才能使用feed获取我的数组:
private void getData() {
//Adding the method to the queue by calling the method getDataFromServer
requestQueue.add(getDataFromServer(requestCount));
//Incrementing the request counter
requestCount++;
}
//Request to get json from server we are passing an integer here
//This integer will used to specify the page number for the request ?page = requestcount
//This method would return a JsonArrayRequest that will be added to the request queue
private JsonArrayRequest getDataFromServer(int requestCount) {
//JsonArrayRequest of volley
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(URL_INDEX + String.valueOf(requestCount),
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
//Calling method parseData to parse the json response
parseData(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//If an error occurs that means end of the list has reached
Toast.makeText(getActivity(), "No More Items Available", Toast.LENGTH_SHORT).show();
}
});
//Returning the request
return jsonArrayRequest;
}
谢谢!
答案 0 :(得分:2)
使用此代码,将 JsonArrayRequest 更改为 JsonObjectRequest
JsonObjectRequest jsonArrayRequest = new JsonObjectRequest(Request.Method.GET, MY_URL, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
//parseData to parse the json response
parseData(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//If an error occurs that means end of the list has reached
Toast.makeText(getActivity(), "No More Items Available", Toast.LENGTH_SHORT).show();
}
});
数组响应
"images": [{
"product_serial_num": "1",
"product_title": "Abbadon",
"product_img": "http://1.2.3.4/android/uploads/1.jpg",
"product_price": "750",
"product_description": "The destroyer"
}]
对象响应
{
"images": [{
"product_serial_num": "1",
"product_title": "Abbadon",
"product_img": "http://1.2.3.4/android/uploads/1.jpg",
"product_price": "750",
"product_description": "The destroyer"
}]
}