码迷,mamicode.com
首页 > 其他好文 > 详细

Gson整合Volley返回对象--GsonRequest

时间:2015-04-08 12:48:34      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/summers/p/4401956.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!