使用JSONObject作为参数的Volley JSONArrayRequest

时间:2016-08-30 19:24:02

标签: android json android-volley

我需要使用JSONObject发出请求,如下所示:

{
    'LangIDs': [1, 2],
    'GenreIDs': [4],
    'LowPrice': 0,
    'HighPrice': 999,
    'SearchTerms': [],
    'Pagination': {
        'PageNumber': 0,
        'PageLength': 10
    }
}

预期的响应是JSONArray。使用Volley,我无法使用JSONObject参数创建JsonArrayRequest。

在我以这种方式提出请求之前:

StringRequest jsonObjectRequest = new StringRequest(Request.Method.POST, url, new Response.Listener < String > () {
    @Override
    public void onResponse(String response) {
        JSONObject jsonObject;
        int id;
        String bookName;
        String Url;
        try {
            responseArray = new JSONArray(response);
        } catch (JSONException e) {

        }

        for (int i = 0; i < response.length(); i++) {
            try {
                jsonObject = responseArray.getJSONObject(i);
                id = jsonObject.getInt(Constants.KEY_ID);
                bookName = jsonObject.getString(Constants.KEY_BOOKNAME);
                Url = imgUrl + jsonObject.getString(Constants.KEY_IMG_URL);
                books.add(new Book(id, bookName, Url));

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        mAdapter.updateGrid(books);
        Log.v("Response", response);
    }
}, new Response.ErrorListener() {@
    Override
    public void onErrorResponse(VolleyError error) {
        Log.e("Error:", error.getMessage());
    }
}) {@
    Override
    protected Map < String, String > getParams() throws AuthFailureError {
        HashMap < String, String > params = new HashMap < > ();
        String message = getArguments().getString(Constants.KEY_FILTER_VALUES);
        Log.v("FilterMessage", message);
        params.put(Constants.KEY_PAGENUMBER, String.valueOf(0));
        params.put(Constants.KEY_PAGELENGTH, String.valueOf(10));
        return params;
    }
};

但现在它是包含JSONObject的JSONObject。

现在我如何使用Volley提出此请求?

3 个答案:

答案 0 :(得分:8)

我创建了一个自定义排球请求,接受JSONObject作为参数。

<强> CustomJsonArrayRequest.java

 public class CustomJsonArrayRequest extends JsonRequest<JSONArray> {

        /**
         * Creates a new request.
         * @param method the HTTP method to use
         * @param url URL to fetch the JSON from
         * @param jsonRequest A {@link JSONObject} to post with the request. Null is allowed and
         *   indicates no parameters will be posted along with request.
         * @param listener Listener to receive the JSON response
         * @param errorListener Error listener, or null to ignore errors.
         */
        public CustomJsonArrayRequest(int method, String url, JSONObject jsonRequest,
                                Listener<JSONArray> listener, ErrorListener errorListener) {
            super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
                    errorListener);
        }

        @Override
        protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
            try {
                String jsonString = new String(response.data,
                        HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
                return Response.success(new JSONArray(jsonString),
                        HttpHeaderParser.parseCacheHeaders(response));
            } catch (UnsupportedEncodingException e) {
                return Response.error(new ParseError(e));
            } catch (JSONException je) {
                return Response.error(new ParseError(je));
            }
        }
    }

如何使用?

JSONObject body = new JSONObject();
// Your code, e.g. body.put(key, value);
CustomJsonArrayRequest req = new CustomJsonArrayRequest(Request.Method.POST, url, body, success, error);

答案 1 :(得分:0)

如果您的请求未发送和接收JSONArray,则无法扩展JsonArrayRequest;与JsonObjectRequest相同

为此你必须使用StringRequest,你应该覆盖getParams()以给它你的JSONObject参数。

StringRequest customRequest = new new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> requestInfo = new HashMap();

            //here add to your the request payload
            requestInfo.put("LowPrice", "0");

            return requestInfo;
        },
        @Override
        public void onResponse(String response) {
            //this code remains the same, 
            //you have to convert the String response to a JSONArray         
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("Error:",error.getMessage());
        }
    });

答案 2 :(得分:-1)

使用以下类将json对象作为参数传递:

public class VolleyJSonRequest {

    public void MakeJsonRequest(final String Tag, String url, final ArrayList<RequestModel> list, final ResponceLisnter responceLisnter, final String HeaderKey) {

        Map<String, String> params = new HashMap<String, String>();
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                //MyLog.ShowLog(list.get(i).getKey(), list.get(i).getValue());
                params.put(list.get(i).getKey(), list.get(i).getValue());

            }
        }
        JSONObject obj = new JSONObject(params);
        JsonArrayRequest jsObjRequest = new JsonArrayRequest
                (Request.Method.POST, url, obj, new Response.Listener<JSONArray>() {

                    @Override
                    public void onResponse(JSONArray response) {
                        try {
//                            Iterator x = response.keys();
//                            JSONArray jsonArray = new JSONArray();
//
//                            while (x.hasNext()){
//                                String key = (String) x.next();
//                                jsonArray.put(response.get(key));
//                            }
                            responceLisnter.getResponce(response.toString(), Tag);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(com.android.volley.VolleyError error) {
                        // TODO Auto-generated method stub
                        if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                            responceLisnter.getResponceError(VolleyError.TIMEOUT_ERROR, Tag);
                        } else if (error instanceof AuthFailureError) {
                            responceLisnter.getResponceError(VolleyError.AUTH_ERROR, Tag);
                        } else if (error instanceof ServerError) {
                            error.printStackTrace();
                            responceLisnter.getResponceError(VolleyError.SERVER_ERROR, Tag);
                        } else if (error instanceof NetworkError) {
                            responceLisnter.getResponceError(VolleyError.NETWORK_ERROR, Tag);
                        }

                    }
                }) {

            /**
             * Passing some request headers
             * */
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", HeaderKey);
                return headers;
            }


        };
        ;

        TestVolleyJson.getInstance().getRequestQueue().add(jsObjRequest);
        jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(50000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }
}

在您的Application类中:

public class TestVolleyJson extends Application {
    private static TestVolleyJson mInstance;
    public static Context context;
    private RequestQueue mRequestQueue;
    public static synchronized TestVolleyJson getInstance() {
        return mInstance;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        mInstance = this;

        mRequestQueue = Volley.newRequestQueue(this);
    }

    public RequestQueue getRequestQueue() {
        return mRequestQueue;
    }
}

发出requestModel:

 public class RequestModel {

    String Key;
    String Value;

    public ArrayList<JSONObject> getJsonObjects() {
        return jsonObjects;
    }

    public void setJsonObjects(ArrayList<JSONObject> jsonObjects) {
        this.jsonObjects = jsonObjects;
    }

    ArrayList<JSONObject> jsonObjects;

    public RequestModel(String key, String value) {
        this.Key = key;
        this.Value = value;
    }
    public RequestModel(String key, ArrayList<JSONObject> jsonObjects) {
        this.Key = key;
        this.jsonObjects = jsonObjects;
    }

    public String getValue() {
        return Value;
    }

    public void setValue(String value) {
        Value = value;
    }

    public String getKey() {
        return Key;
    }

    public void setKey(String key) {
        Key = key;
    }

}

并在您的活动中:

   VolleyJSonRequest  volleyJSonRequest = new VolleyJSonRequest();



   ArrayList<RequestModel> list = new ArrayList<>();
    list.add(new RequestModel("Param1", "abc"));
    list.add(new RequestModel("Param2", "xyz"));
    volleyJSonRequest.MakeJsonRequest("Tag", "URL", list, responceLisnter, "application/json; charset=utf-8");
}

ResponceLisnter responceLisnter = new ResponceLisnter() {
    @Override
    public void getResponce(String str, String Tag) throws JSONException {
        if (Tag.equalsIgnoreCase("Logintest")) {
            Log.e(Tag, " Response is" + str);
        }
    }

    @Override
    public void getResponceError(String errorStr, String Tag) {

    }
    };

建立一个响应者界面:

public interface ResponceLisnter {

    void getResponce(String str, String Tag) throws JSONException;

    void getResponceError(String errorStr, String Tag);
}

希望它对您有用