【发布时间】:2017-03-29 10:22:33
【问题描述】:
我正在使用 Google 的 Volley 使用以下自定义请求类发出 GET 和 POST 请求:
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"
}
对这个问题有帮助吗?
【问题讨论】:
-
stackoverflow.com/questions/10498000/… 你试过添加
JsonArray吗? -
我正在从另一个类发送 JSONArray 参数,如下所示:
params.put(PRICE, new JSONArray(mPricesList).toString()); -
@chirag90,它不是重复的,我使用的是自定义请求,而不是 JSONArrayRequest。我在发布我的问题之前进行了搜索。谢谢
-
有人有答案吗?
标签: android json android-volley