我正在尝试使用android volley发出Gson请求。目前它正常工作,我很高兴。但是为什么我尝试获取List<>或者我的代码不再有效的对象集合。
当前代码:
public class ReviewModel
{
public long Id;
public Strring Description;
}
这是我如何使用我的gson类:
GsonRequest<ReviewModel> jsObjRequest = new GsonRequest<ReviewModel>(Request.Method.GET,
url, ReviewModel.class, new Response.Listener<ReviewModel>() {
@Override
public void onResponse(ReviewModel response) {
ReviewsHandleOkResponse(response);
}
}, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
ReviewsHandleErrorResponse(error);
}
});
Network.getInstance(getActivity()).addToRequestQueue(jsObjRequest);
}
这是我的Volley GSON请求类:
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> params;
private final Listener<T> listener;
/**
* Make a GET request and return a parsed object from JSON.
*
* @param url
* URL of the request to make
* @param clazz
* Relevant class object, for Gson's reflection
* @param headers
* Map of request headers
*/
public GsonRequest(int method, String url, Class<T> clazz,
Map<String, String> headers, Map<String, String> params,
Listener<T> listener, ErrorListener errorListener) {
super(method, Network.getFullUrl(url), errorListener);
this.clazz = clazz;
this.headers = headers;
this.params = params;
this.listener = listener;
}
/**
* Recieves header
*
* @param method
* @param url
* @param clazz
* @param params
* @param listener
* @param errorListener
*/
public GsonRequest(int method, String url, Class<T> clazz,
Map<String, String> params, Listener<T> listener,
ErrorListener errorListener) {
super(method, Network.getFullUrl(url), errorListener);
this.clazz = clazz;
this.headers = new HashMap<String, String>();
this.params = params;
this.listener = listener;
}
/**
* No params or headers
*
* @param method
* @param url
* @param clazz
* @param listener
* @param errorListener
*/
public GsonRequest(int method, String url, Class<T> clazz,
Listener<T> listener, ErrorListener errorListener) {
super(method, Network.getFullUrl(url), errorListener);
this.clazz = clazz;
this.headers = new HashMap<String, String>();
this.params = new HashMap<String, String>();
this.listener = listener;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}
@Override
public Map<String, String> getParams() throws AuthFailureError {
return params != null ? params : super.getParams();
}
@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));
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));
}
}
}
然而,当我将它重新解析并解析为List<ReviewModel>
时,我会遇到编译错误。
根据我的研究,我需要做一些事情:
Type collectionType = new TypeToken<ArrayList<ReviewModel>>(){}.getType();
// api/v1/reviews/products/{productId}/{pageNumber}/{pageSize}
String url = "api/v1/reviews/products/" + productId + "/" + currentPage + "/" + pageSize;
GsonRequest<ArrayList<ReviewModel>> jsObjRequest = new GsonRequest<ArrayList<ReviewModel>>(Request.Method.GET,
url, (Class<ArrayList<ReviewModel>>) collectionType, new Response.Listener<ArrayList<ReviewModel>>() {
@Override
public void onResponse(ArrayList<ReviewModel> response) {
ReviewsHandleOkResponse(response);
}
}, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
ReviewsHandleErrorResponse(error);
}
});
Network.getInstance(getActivity()).addToRequestQueue(jsObjRequest);
}
但是这给了我以下错误:
10-28 21:12:59.940:E / AndroidRuntime(28564): java.lang.RuntimeException:无法启动活动 ComponentInfo {} com.menu/com.menu.activities.ProductViewActivity: java.lang.ClassCastException: com.google.gson.internal。$ Gson $ Types $ ParameterizedTypeImpl不能 强制转换为java.lang.Class
我是否需要修改我的GsonRequest类,并添加另一个不带类型类的构造函数?
答案 0 :(得分:3)
将YourClass[]
用于Volley请求中的对象列表。它解决了我的问题。以下代码可以帮助您:
GsonRequest<ReviewModel[]> jsObjRequest = new GsonRequest<ReviewModel[]>(Request.Method.GET,
url, ReviewModel[].class, new Response.Listener<ReviewModel[]>() {
@Override
public void onResponse(ReviewModel[] response) {
ReviewsHandleOkResponse(response);
}
}, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
ReviewsHandleErrorResponse(error);
}
});
Network.getInstance(getActivity()).addToRequestQueue(jsObjRequest);
}
答案 1 :(得分:1)
我最近需要自己实施一个解决方案,所以你走了。 自定义GsonArrayRequest。
public class GsonArrayRequest<T> extends Request<ArrayList<T>> {
private final Gson gson = new Gson();
private final Class<T> clazz;
private final Map<String, String> headers;
private final Response.Listener<ArrayList<T>> listener;
/**
* Make a GET request and return a parsed object from JSON.
* @param clazz Relevant class object, for Gson's reflection
* @param url URL of the request to make
* @param headers Map of request headers
*/
public GsonArrayRequest(String url, Class<T> clazz, Map<String, String> headers,
Response.Listener<ArrayList<T>> listener, Response.ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.clazz = clazz;
this.headers = headers;
this.listener = listener;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}
@Override
protected Response<ArrayList<T>> parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(
response.data,
HttpHeaderParser.parseCharset(response.headers));
Type listType = com.google.gson.internal.$Gson$Types.newParameterizedTypeWithOwner(null, ArrayList.class, clazz);
ArrayList<T> tList = gson.fromJson(json, listType);
return Response.success(
tList,
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
@Override
protected void deliverResponse(ArrayList<T> response) {
listener.onResponse(response);
}
}
你可以像这样使用它:
GsonArrayRequest<StoreWorkout> gsonArrayRequest = new GsonArrayRequest<>(
url, AngryPugs.class, null, new Response.Listener<ArrayList<AngryPugs>>() {
@Override
public void onResponse(ArrayList<AngryPugs> response) {
// your list here
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
添加请求后
VolleySingleton.getInstance(this).addToRequestQueue(gsonArrayRequest);