Gson整合Volley返回对象--GsonRequest

Gson是一个使用映射支持JSON与Java对象之间相互转换的库文件。你可以定义和JSON keys相对应名称的Java对象。把对象传递给传递Gson,然后Gson会帮你为对象填充字段值。 下面是一个完整的示例:演示了使用Gson解析Volley数据:

 1 public class GsonRequest<T> extends Request<T> {
 2     private final Gson gson = new Gson();
 3     private final Class<T> clazz;
 4     private final Map<String, String> headers;
 5     private final Listener<T> listener;
 6 
 7     /**
 8      * Make a GET request and return a parsed object from JSON.
 9      *
10      * @param url URL of the request to make
11      * @param clazz Relevant class object, for Gson's reflection
12      * @param headers Map of request headers
13      */
14     public GsonRequest(String url, Class<T> clazz, Map<String, String> headers,
15             Listener<T> listener, ErrorListener errorListener) {
16         super(Method.GET, url, errorListener);
17         this.clazz = clazz;
18         this.headers = headers;
19         this.listener = listener;
20     }
21 
22     @Override
23     public Map<String, String> getHeaders() throws AuthFailureError {
24         return headers != null ? headers : super.getHeaders();
25     }
26 
27     @Override
28     protected void deliverResponse(T response) {
29         listener.onResponse(response);
30     }
31 
32     @Override
33     protected Response<T> parseNetworkResponse(NetworkResponse response) {
34         try {
35             String json = new String(
36                     response.data,
37                     HttpHeaderParser.parseCharset(response.headers));
38             return Response.success(
39                     gson.fromJson(json, clazz),
40                     HttpHeaderParser.parseCacheHeaders(response));
41         } catch (UnsupportedEncodingException e) {
42             return Response.error(new ParseError(e));
43         } catch (JsonSyntaxException e) {
44             return Response.error(new ParseError(e));
45         }
46     }
47 }

 

你可能感兴趣的:(Gson整合Volley返回对象--GsonRequest)