0

I am using Google's Volley to make GET and POST requests using the following custom request class:

public class GsonRequest<T> extends Request<T> {

    private static final int SOCKET_TIMEOUT_MS = 30000;
    private static final int MAX_RETRIES = 3;

    private final Gson gson = new Gson();
    private final Type type;
    private final Map<String, String> params;
    private final Response.Listener<T> listener;

    /**
     * Make a GET request and return a parsed object from JSON.
     *
     * @param url    URL of the request to make
     * @param type   Relevant type object, for Gson's reflection
     * @param params Map of request params
     */
    public GsonRequest(int method, String url, Type type, Map<String, String> params,
                       Response.Listener<T> listener, Response.ErrorListener errorListener) {
        super(method, url, errorListener);
        this.type = type;
        this.params = params;
        this.listener = listener;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return headers;
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        // Here is my question, can I add a param value as JSONArray? like this:
        params.put("orderValue", "35");
        params.put("price", ""price": ["13.00", "22.00"]");
        return params != null ? params : super.getParams();
    }

    @Override
    public Request<?> setRetryPolicy(RetryPolicy retryPolicy) {
        final RetryPolicy policy = new DefaultRetryPolicy(SOCKET_TIMEOUT_MS, MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        return super.setRetryPolicy(policy);
    }

    @Override
    public String getBodyContentType() {
        return "application/json";
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        try {
            Log.i("" + gson.toJson(params).getBytes("utf-8"));
            return gson.toJson(params).getBytes("utf-8");
        } catch (UnsupportedEncodingException uee) {
            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", gson.toJson(params), "utf-8");
            return super.getBody();
        }
    }

    @Override
    protected void deliverResponse(T response) {
        listener.onResponse(response);
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            final String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            return (Response<T>) Response.success(gson.fromJson(json, type), HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JsonSyntaxException e) {
            return Response.error(new ParseError(e));
        }
    }
}

The Json I'm trying to send:

{
  "orderValue": "35",
  "price": [
    "13.00",
    "22.00"
  ]
}

What is really sent as I get from getBody() method log is:

{
  "price": "[\"23.00\",\"55.00\"]",
  "orderValue": "35"
}

Any help with this issue?

4
  • stackoverflow.com/questions/10498000/… Have you tried adding a JsonArray?
    – Maximosaic
    Mar 29, 2017 at 10:26
  • I am sending the JSONArray param from another class like this: params.put(PRICE, new JSONArray(mPricesList).toString());
    – blueware
    Mar 29, 2017 at 10:29
  • @chirag90, its not a duplicate, I am using custom request, not a JSONArrayRequest. I did search before posting my question. Thanks
    – blueware
    Mar 29, 2017 at 10:32
  • Anyone has an answer?
    – blueware
    Mar 29, 2017 at 13:45

1 Answer 1

0

You need change extends Request to ** JsonObjectRequest** or create JSONArrayRequest object.

public class VolleyJSONObjectRequest extends JsonObjectRequest {

    private Context context;
    private int timeOut = 10000;
    private int maxRetries = 1;

    public VolleyJSONObjectRequest(int method, Context context, String url, JSONObject jsonObject, Listener<JSONObject> listener, ErrorListener errorListener) {
        super(method, url, jsonObject, listener, errorListener);
        super.setRetryPolicy(new DefaultRetryPolicy(timeOut, maxRetries, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }

    public void startRequest() {
        VolleyHandler.get(context).addToRequestQueue(this);
    }
}

Example method:

private void saveItems(){
        if  (itens != null && itens.size() > 0) {
            try {
                JSONArray itensJson = new JSONArray();

                for (SalesOrderItem item : itens) { // your loop

                    JSONObject jsonObject = new JSONObject();

                    jsonObject.put("price", this.priceOne);
                    jsonObject.put("price", this.priceTwo);

                    itensJson.put(jsonObject);
                }

                JSONObject headerJSON = new JSONObject();
                headerJSON.put("price", itensJson);

                VolleyJSONObjectRequest request = new VolleyJSONObjectRequest(Request.Method.POST, context, context.getString(R.string.URL_SALES_ORDER_ITENS_INSERT), headerJSON, onResponseItem, onErrorResponseItem);
                request.startRequest();

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

  request = new VolleyStringRequest(context, context.getString(R.string.URL_FINISH_SALES_ORDER_DRAFT), onResponseFinishSalesOrderDraft, onErrorResponseFinishSalesOrderDraft);
  request.startRequest();
1
  • This does not work, the API does not accept separate JSONArray values like price[0], price[1], ...,etc.
    – blueware
    Mar 30, 2017 at 8:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.