java android使用Gson解析泛型json数据

那就直接开始吧。

在我们获取服务器返回的json数据有时候会出现这种情况,比如:

{"body":{"attrName":"feed","result":[{"time":63000000,"food":14,"id":2,}]},"when":"20180426170357+0800"}
{"body":{"attrName":"media","result":{"singer":"薛之谦","name":"你还要我怎样"}},"when":"20180426170357+0800"}

两条数据其他结构相同,但前者的"result"是一个json数组,而后者直接是一条json字符串。

此时我们可以将实体类这样写:

 1 public class ReportBean<T>{
 2 
 3     private Body<T> body;
 4     private String when;
 5 
 6     public Body<T> getBody() {
 7         return body;
 8     }
 9 
10     public void setBody(Body<T> body) {
11         this.body= body;
12     }
13 
14     public String getWhen() {
15         return when;
16     }
17 
18     public void setWhen(String when) {
19         this.when = when;
20     }
21 
22     public class Body<T>  {
23 
24         private String attrName;
25         private T result;
26 
27         public String getAttrName() {
28             return attrName;
29         }
30 
31         public void setAttrName(String attrName) {
32             this.attrName = attrName;
33         }
34 
35         public T getResult() {
36             return result;
37         }
38 
39         public void setResult(T result) {
40             this.result = result;
41         }
42 
43     }
44 }

接下来,当我们处理数据时——

第一种,json数组:

Type  jsonType = new TypeToken<ReportBean<List<ResultBean>>>() {}.getType();

ReportBean<List<ResultBean>> reportBean = new Gson().fromJson(jsonStr, jsonType);

要获取的泛型数组即bean.getBody().getResult;


第二种,json字符串:

Type  jsonType = new TypeToken<ReportBean<ResultBean2>>() {}.getType();

ReportBean<ResultBean2> reportBean = new Gson().fromJson(jsonStr, jsonType);

ResultBean即为自定义的泛型中具体的数据实体类,此时数据就都已经解析到 reportBean 里面了,再根据自己的需要取出即可。

猜你喜欢

转载自www.cnblogs.com/Sharley/p/8954055.html