我有一个通用的 sendRequest() 方法,用于从服务器返回 json 结果。我现在正在解析回调实例中的结果,但我宁愿只将类型传递给 sendRequest() 方法,以便我可以在回调之前解析和处理异常。我怎样才能做到这一点?我在下面添加了相关代码和一些注释。
public void sendRequest(int method, String url, final RequestListener listener) {
StringRequest postRequest = new StringRequest(method, url,
new Response.Listener<String>()
{
@Override
public void onResponse(String response) {
listener.gotResponse(response, null);
// Instead of parsing this into a user object, I'd like to parse it into
// a type that I pass into the sendRequest() method.
try {
User user = User.parseJson(new JSONObject(response));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
最佳答案
首先请注意,开箱即用的 JsonObjectRequest
会将响应直接转换为 JSONObject
,这似乎比 StringRequest
在你的情况下,但当你想更进一步时,我建议创建一个 custom request基于通用解码器。
public interface JsonUnmarshaller<T> {
T parse(JSONObject object) throws JSONException;
}
自定义请求可能是这样的:
public class JSONRequest extends Request<T> {
private final Listener<T> mListener;
private final JsonUnmarshaller<T> unmarshaller;
public JSONRequest(int method, String url, Listener<T> listener,
ErrorListener errorListener, JsonUnmarshaller<T> unmarshaller) {
super(method, url, errorListener);
mListener = listener;
this.unmarshaller = unmarshaller;
}
@Override
protected void deliverResponse(T response) {
mListener.onResponse(response);
}
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(
response.data, HttpHeaderParser.parseCharset(response.headers)
);
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
try {
return Response.success(
unmarshaller.parse(new JSONObject(parsed)),
HttpHeaderParser.parseCacheHeaders(response)
);
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}
那么你的方法是:
public <T> void sendRequest(int method, String url, final RequestListener
listener, JsonUnmarshaller<T> unmarshaller) {
JSONRequest postRequest = new JSONRequest(...
关于java - 在 Java 中创建泛型类和参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39518470/