我使用android开发者网站引用创建自定义请求类的截击,我可以将参数作为HashMap发送如下
Map<String,String> params = new HashMap<String, String>();
params.put("place","bur");
但是现在我想将参数作为json字符串传递给服务器。我怎么能通过这个?
{"place":"bur"}
这是我的自定义请求类
public class GsonRequest<T> extends Request<T> {
private final Gson gson = new Gson();
private final Class<T> clazz;
private final Map<String, String> headers;
private final Map<String, String> parms;
private final Listener<T> listener;
public GsonRequest(String url, int method, Class<T> clazz, Map<String, String> headers,
Map<String, String> parms, Listener<T> listener, ErrorListener errorListener) {
super(method, url, errorListener);
this.clazz = clazz;
this.headers = headers;
this.listener = listener;
this.parms = parms;
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
return parms != null ? parms : super.getParams();
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}
@Override
protected void deliverResponse(T response) {
listener.onResponse(response);
}
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
Log.i("json", json);
return Response.success(gson.fromJson(json, clazz),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
答案 0 :(得分:0)
我主要使用这两种方式来处理JSON响应:
使用org.json包(JSONObject和JSONArray)。这样您就不会立即获取对象,而是逐行反汇编响应。例如,我编写了此代码来处理Google Distance Matrix响应并获取持续时间文本(response example here):
JSONObject responseObject = new JSONObject(response);
JSONObject row = responseObject.getJSONArray("rows").getJSONObject(0);
JSONObject element = row.getJSONArray("elements").getJSONObject(0);
String status = element.getString("status");
String durationText = element.getJSONObject("duration").getString("text");
使用Gson解析响应。使用此模块,您可以直接按照要求获取课程。您需要创建一个完全符合您的响应的类,并按照以下方式处理它:
ResponseClass responseClass = new Gson().fromJson(response, ResponseClass.class);
你可以得到Gson here。重点是您不需要自定义响应才能使用它。