Android volley使用接受JSONArray参数的getParams实现自定义请求

时间:2017-03-29 10:22:34

标签: android json android-volley

我正在使用Google Volley使用以下自定义请求类发出GETPOST个请求:

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

Json我试图发送:

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

我从getBody()方法日志获得的真实内容是:

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

有关此问题的任何帮助吗?

1 个答案:

答案 0 :(得分:0)

您需要将请求更改为** JsonObjectRequest **或创建 JSONArrayRequest 对象。

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

示例方法:

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