Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

android - Volley JSONArrayRequest with JSONObject as parameter

I need to make a request with a JSONObject as follows:

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

The expected response is a JSONArray. Using Volley, I can't make a JsonArrayRequest with a JSONObject parameter.

Before I made the request this way:

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;
    }
};

But now it is JSONObject that contains JSONObject.

How now I can make this request using Volley?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I created a custom volley request that accepts a JSONObject as parameter.

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));
            }
        }
    }

How to use?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...