java android uses Gson to parse generic json data

Then just get started.

This sometimes happens when we get the json data returned by the server, for example:

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

The other structures of the two pieces of data are the same, but the "result" of the former is a json array, while the latter is a json string directly.

At this point we can write the entity class like this:

 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 }

Next, when we process the data -

The first, json array:

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

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

The generic array to be obtained is bean.getBody().getResult;


The second, json string:

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

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

 

ResultBean is the specific data entity class in the custom generic type. At this time, the data has been parsed into the reportBean, and then it can be taken out according to its own needs.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324975240&siteId=291194637