Gson について私が気に入らなかった点の 1 つは、アイテムまたはアイテムのリストを取得するかどうかに基づいて、Class オブジェクトまたは TypeToken を渡す必要があるという事実です。現在、Gson で Volley を使用しようとすると、この問題が解決せず、両方に使用できる GsonRequest クラスを作成しようとしています。
私の解決策は非常に醜く、2 つの異なるコンストラクターです。1 つはClass<T>
パラメーターを取得し、もう 1 つはパラメーターを取得しType
ます。次に、フィールドのいずれかparseNetworkResponse
で gson.fromJson
が呼び出されますが、いずれかが である必要があることに注意してnull
ください。
これをより良い方法で実装する方法について何か考えはありますか? GsonRequest
( aと a がGsonCollectionRequest
ほぼ等しいクラスを持つのは好きではありません)
ここに私のコード:
public class GsonRequest<T> extends Request<T> {
private final Gson gson;
private final Class<T> clazz;
private final Type type;
private final Listener<T> listener;
private final Map<String, String> headers;
private final Map<String, String> params;
public GsonRequest(int method, String url, Gson gson, Class<T> clazz, Map<String, String> headers, Map<String, String> params, Listener<T> listener, ErrorListener errorListener) {
super(method, url, errorListener);
this.gson = gson;
this.clazz = clazz;
this.type = null;
this.listener = listener;
this.headers = headers;
this.params = params;
}
public GsonRequest(int method, String url, Gson gson, Type type, Map<String, String> headers, Map<String, String> params, Listener<T> listener, ErrorListener errorListener) {
super(method, url, errorListener);
this.gson = gson;
this.clazz = null;
this.type = type;
this.listener = listener;
this.headers = headers;
this.params = params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return this.headers != null ? this.headers : super.getHeaders();
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
return this.params != null ? this.params : super.getParams();
}
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
if (this.clazz != null) {
return Response.success(
this.gson.fromJson(new String(response.data, HttpHeaderParser.parseCharset(response.headers)), this.clazz),
HttpHeaderParser.parseCacheHeaders(response));
} else {
return (Response<T>) Response.success(
this.gson.fromJson(new String(response.data, HttpHeaderParser.parseCharset(response.headers)), this.type),
HttpHeaderParser.parseCacheHeaders(response));
}
} catch (JsonSyntaxException e) {
e.printStackTrace();
return Response.error(new ParseError(e));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return Response.error(new ParseError(e));
}
}
@Override
protected void deliverResponse(T response) {
this.listener.onResponse(response);
}
}