欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java-JSON

程序员文章站 2022-08-21 13:14:45
fastJson GSON GSON2 ......

 

 1         <!-- fastjson -->
 2         <dependency>
 3             <groupid>com.alibaba</groupid>
 4             <artifactid>fastjson</artifactid>
 5             <version>1.2.47</version>
 6         </dependency>
 7 
 8         <!-- gson -->
 9         <dependency>
10             <groupid>com.google.code.gson</groupid>
11             <artifactid>gson</artifactid>
12             <version>2.8.2</version>
13         </dependency>

fastjson

  1 import static com.alibaba.fastjson.util.typeutils.casttoboolean;
  2 
  3 import java.io.serializable;
  4 import java.lang.reflect.type;
  5 import java.util.arraylist;
  6 import java.util.collection;
  7 import java.util.iterator;
  8 import java.util.list;
  9 import java.util.listiterator;
 10 import java.util.randomaccess;
 11 
 12 import com.alibaba.fastjson.json;
 13 import com.alibaba.fastjson.jsonobject;
 14 import com.alibaba.fastjson.parser.parserconfig;
 15 import com.alibaba.fastjson.util.typeutils;
 16 
 17 /**
 18  * jsonarray源码
 19  */
 20 public class jsonarray1 extends json implements list<object>, cloneable, randomaccess, serializable {
 21 
 22     private final list<object> list;
 23     protected transient object relatedarray;
 24     protected transient type   componenttype;
 25     //使用无参构造创建jsonarray的时候,初始化一个空arraylist
 26     public jsonarray1(){
 27         this.list = new arraylist<object>();
 28     }
 29     //使用有参构造,将参数list赋值给jsonarray的属性list
 30     public jsonarray1(list<object> list){
 31         this.list = list;
 32     }
 33     //使用无参构造,创建指定参数大小的list
 34     public jsonarray1(int initialcapacity){
 35         this.list = new arraylist<object>(initialcapacity);
 36     }
 37 
 38     //set和get方法
 39     public object getrelatedarray() {return relatedarray;}
 40     public void setrelatedarray(object relatedarray){this.relatedarray = relatedarray;}
 41     public type getcomponenttype() {return componenttype;}
 42     public void setcomponenttype(type componenttype){this.componenttype = componenttype;}
 43 
 44     //获取存储数据的list的大小
 45     public int size() {
 46         return list.size();
 47     }
 48     //判断存储数据的list是否为空
 49     public boolean isempty() {
 50         return list.isempty();
 51     }
 52     //判断存储数据的list是否包含某个对象
 53     public boolean contains(object o) {
 54         return list.contains(o);
 55     }
 56     //获取存储数据的list的迭代器对象
 57     public iterator<object> iterator() {
 58         return list.iterator();
 59     }
 60     //将存储数据的list转成数组
 61     public object[] toarray() {
 62         return list.toarray();
 63     }
 64     //将参数中的数据,添加list中,并将list转成参数中数组的类型的数组返回
 65     public <t> t[] toarray(t[] a) {
 66         return list.toarray(a);
 67     }
 68     //向存储数据的list中添加元素,添加成功返回true
 69     public boolean add(object e) {
 70         return list.add(e);
 71     }
 72     //向存储数据的list中添加元素,返回该jsonarray对象
 73     public jsonarray1 fluentadd(object e) {
 74         list.add(e);
 75         return this;
 76     }
 77     //从存储数据的list中移除指定元素,移除成功返回true
 78     public boolean remove(object o) {
 79         return list.remove(o);
 80     }
 81     //从存储数据的list中移除指定元素,返回该jsonarray对象
 82     public jsonarray1 fluentremove(object o) {
 83         list.remove(o);
 84         return this;
 85     }
 86     //判断list中是否包含指定集合中的所有元素
 87     public boolean containsall(collection<?> c) {
 88         return list.containsall(c);
 89     }
 90     //添加指定集合中的所有元素到list中,添加成功返回true
 91     public boolean addall(collection<? extends object> c) {
 92         return list.addall(c);
 93     }
 94     //添加指定集合中的所有元素到list中,返回该jsonarray对象
 95     public jsonarray1 fluentaddall(collection<? extends object> c) {
 96         list.addall(c);
 97         return this;
 98     }
 99     //添加指定集合中的所有元素到list中指定下标处,添加成功返回true
100     public boolean addall(int index, collection<? extends object> c) {
101         return list.addall(index, c);
102     }
103     //添加指定集合中的所有元素到list中指定下标处,返回该jsonarray对象
104     public jsonarray1 fluentaddall(int index, collection<? extends object> c) {
105         list.addall(index, c);
106         return this;
107     }
108     //从list中删除指定集合中的所有元素,删除成功返回true
109     public boolean removeall(collection<?> c) {
110         return list.removeall(c);
111     }
112     //从list中删除指定集合中的所有元素,返回该jsonarray对象
113     public jsonarray1 fluentremoveall(collection<?> c) {
114         list.removeall(c);
115         return this;
116     }
117     
118     public boolean retainall(collection<?> c) {
119         return list.retainall(c);
120     }
121 
122     public jsonarray1 fluentretainall(collection<?> c) {
123         list.retainall(c);
124         return this;
125     }
126     //清空list集合
127     public void clear() {
128         list.clear();
129     }
130     //清空list并返回jsonarray对象
131     public jsonarray1 fluentclear() {
132         list.clear();
133         return this;
134     }
135     //添加元素到list的指定下标处
136     public object set(int index, object element) {
137         if (index == -1) {
138             list.add(element);
139             return null;
140         }
141         
142         if (list.size() <= index) {
143             for (int i = list.size(); i < index; ++i) {
144                 list.add(null);
145             }
146             list.add(element);
147             return null;
148         }
149         
150         return list.set(index, element);
151     }
152     //添加元素到指定下标处,返回jsonarray对象
153     public jsonarray1 fluentset(int index, object element) {
154         set(index, element);
155         return this;
156     }
157     //添加元素到指定下标
158     public void add(int index, object element) {
159         list.add(index, element);
160     }
161     //添加元素到指定下标处,返回jsonarray对象
162     public jsonarray1 fluentadd(int index, object element) {
163         list.add(index, element);
164         return this;
165     }
166     //删除并返回指定下标处的元素
167     public object remove(int index) {
168         return list.remove(index);
169     }
170     //删除指定下标处的元素,返回jsonarray对象
171     public jsonarray1 fluentremove(int index) {
172         list.remove(index);
173         return this;
174     }
175     //获取元素第一次出现的下标
176     public int indexof(object o) {
177         return list.indexof(o);
178     }
179     //获取元素最后一次出现的下标
180     public int lastindexof(object o) {
181         return list.lastindexof(o);
182     }
183     //获取list特有的迭代器对象
184     public listiterator<object> listiterator() {
185         return list.listiterator();
186     }
187     //根据下标获取list特有的迭代器对象
188     public listiterator<object> listiterator(int index) {
189         return list.listiterator(index);
190     }
191     //截取list
192     public list<object> sublist(int fromindex, int toindex) {
193         return list.sublist(fromindex, toindex);
194     }
195     //根据下标获取元素
196     public object get(int index) {
197         return list.get(index);
198     }
199     //根据下标获取元素,并转成jsonobject对象返回
200     public jsonobject getjsonobject(int index) {
201         object value = list.get(index);
202 
203         if (value instanceof jsonobject) {
204             return (jsonobject) value;
205         }
206 
207         return (jsonobject) tojson(value);
208     }
209     //根据下标获取元素,并转成jsonarray对象返回
210     public jsonarray1 getjsonarray(int index) {
211         object value = list.get(index);
212 
213         if (value instanceof jsonarray1) {
214             return (jsonarray1) value;
215         }
216 
217         return (jsonarray1) tojson(value);
218     }
219     //根据下标获取对象并装成指定的对象类型
220     public <t> t getobject(int index, class<t> clazz) {
221         object obj = list.get(index);
222         return typeutils.casttojavabean(obj, clazz);
223     }
224     //根据下标获取元素,并转成boolean
225     public boolean getboolean(int index) {
226         object value = get(index);
227         if (value == null) {
228             return null;
229         }
230         return casttoboolean(value);
231     }
232     //根据下标获取元素,并转成boolean
233     public boolean getbooleanvalue(int index) {
234         object value = get(index);
235         if (value == null) {
236             return false;
237         }
238         return casttoboolean(value).booleanvalue();
239     }
240     /**
241      * 根据下标获取对应类型的数据
242      * getbyte、getbytevalue、getshort、getshortvalue、getinteger、getintvalue
243      * getlong、getlongvalue、getfloat、getfloatvalue、getdouble、getdoublevalue
244      * getbigdecimal、getbiginteger、getstring、getdate、getsqldate、gettimestamp
245      */
246     //转成指定类型的arraylist对象
247     public <t> list<t> tojavalist(class<t> clazz) {
248         list<t> list = new arraylist<t>(this.size());
249 
250         parserconfig config = parserconfig.getglobalinstance();
251 
252         for (object item : this) {
253             t classitem = (t) typeutils.cast(item, clazz, config);
254             list.add(classitem);
255         }
256 
257         return list;
258     }
259     //复制
260     @override
261     public object clone() {
262         return new jsonarray1(new arraylist<object>(list));
263     }
264     public boolean equals(object obj) {
265         return this.list.equals(obj);
266     }
267     public int hashcode() {
268         return this.list.hashcode();
269     }
270 }

 

 1 import java.util.hashmap;
 2 import java.util.map;
 3 import java.util.map.entry;
 4 import java.util.set;
 5 import com.alibaba.fastjson.json;
 6 import com.alibaba.fastjson.jsonarray;
 7 import com.alibaba.fastjson.jsonobject;
 8 
 9 /**
10  * fastjson常用方法介绍
11  */
12 public class testjson {
13     public static void main(string[] args) {
14         //json字符串
15         string jsonstr = "{'name':'zhangsan','age':'10'}";
16         string jsonstr2 = "{'name':'zhangsan','age':'11'}";
17         //将json字符串解析成jsonobject
18         jsonobject jsonobj = json.parseobject(jsonstr);
19         jsonobject jsonobj2 = json.parseobject(jsonstr2);
20         jsonobj.tojsonstring();//转成json字符串
21         jsonobj.isempty();//判断是否非空
22         jsonobj.containskey("name");//是否包含指定key
23         jsonobj.containsvalue("zhangsan");//是否包含指定value
24         jsonobj.equals(jsonobj2);//判断两个jsonobject是否相等
25         jsonobj.get("name");//使用map中的取值方法获取value
26         jsonobj.getstring("name");//获取指定key对应的value
27         jsonobj.size();//获取长度
28         jsonobj.put("core", "a");//添加元素
29         jsonobj.remove("name");//删除指定key
30         jsonobj.clear();//清空
31         map<string, object> map = new hashmap<string, object>();
32         jsonobj.putall(map);//将指定map中的元素添加到jsonobject中
33         
34         jsonobj.keyset();//获取所有的key
35         jsonobj.values();//获取所有的value
36         
37         set<entry<string, object>> entryset = jsonobj.entryset();//获取所有键值对entry
38         //遍历
39         for (entry<string, object> entry : entryset) {
40             string key = entry.getkey();//获取key
41             string value = (string) entry.getvalue();//获取value
42             entry.setvalue("呵呵");//修改value值
43         }
44         
45         
46         //json字符串转jsonarray
47         string str1 = "[{'name':'zhangsan','age':'10'},{'name':'lisi','age':'20'}]";
48         string str2 = "[{'name':'zhang','age':'15'},{'name':'wangwu','age':'22'}]";
49         jsonarray jsonarray = json.parsearray(str1);
50         
51         string jsonstring = jsonarray.tojsonstring();//转成json字符串
52         
53         //遍历这个jsonarray
54         for (int i = 0; i < jsonarray.size(); i++) {
55             //获取jsonarray中的每一个元素,元素可以为jsonobject、jsonarray
56             jsonobject jsonobject = jsonarray.getjsonobject(i);
57             //然后通过map中的方法entryset()方法获取键值对
58             set<entry<string, object>> entryset2 = jsonobject.entryset();
59             for (entry<string, object> entry : entryset2) {
60                 //然后对entryset2遍历
61                 string key = entry.getkey();
62                 object value = entry.getvalue();
63             }
64         }
65     }
66 }

 

 

gson

 1 /**
 2  * 实体类
 3  */
 4 public class student {
 5     private string name;
 6     private integer age;
 7     
 8     public student() {
 9     }
10     public student(string name, integer age) {
11         super();
12         this.name = name;
13         this.age = age;
14     }
15     public string getname() {
16         return name;
17     }
18     public void setname(string name) {
19         this.name = name;
20     }
21     public integer getage() {
22         return age;
23     }
24     public void setage(integer age) {
25         this.age = age;
26     }
27 }
 1 import java.io.filenotfoundexception;
 2 import java.io.filereader;
 3 import java.util.iterator;
 4 
 5 import com.google.gson.gson;
 6 import com.google.gson.jsonarray;
 7 import com.google.gson.jsonelement;
 8 import com.google.gson.jsonioexception;
 9 import com.google.gson.jsonobject;
10 import com.google.gson.jsonparser;
11 import com.google.gson.jsonsyntaxexception;
12 /**
13  * 读取json文件
14  * jsonobject  就是key和value
15  * jsonelement  就是一个个value  但是对应的value也有很多可能性,例如可以是一个数组,可以是一个json对象
16  */
17 public class jsonanalysis {
18     public static void main(string[] args) {
19         //1.创建一个json解析器
20         jsonparser parser = new jsonparser();
21         try {
22             /**
23              * jsonparser对象中有三个方法:
24              *     parse(jsonreader json)
25              *     parse(reader json)
26              *     parse(string json) 将指定的json字符串解析为解析树
27              */
28                 //2.将流中的json字符串解析并强转成json对象
29                 jsonobject object = (jsonobject) parser.parse(new filereader("test.json"));
30                 
31                 
32                 /**
33                  * jsonelement对象提供了对所有类型获取的方法。
34                  * 
35                  * 获取值的方法:
36                  * getasbigdecimal() 
37                  * getasbiginteger() 
38                  * getasboolean()     
39                  * getasbyte() 
40                  * getascharacter() 
41                  * getasdouble() 
42                  * getasfloat() 
43                  * getasint() 
44                  * getaslong() 
45                  * getasnumber() 
46                  * getasshort() 
47                  * getasstring() 
48                  * 
49                  * getasjsonarray() 
50                  * getasjsonnull() 
51                  * getasjsonobject()     
52                  * getasjsonprimitive() 
53                  * 
54                  * 判断的方法:
55                  * isjsonarray() 是否为一个数组
56                  * isjsonnull()  
57                  * isjsonobject() 
58                  * isjsonprimitive() 
59                  * tostring() 
60                  */
61                 
62                 //连写
63                 string name = object.get("name").getasstring();
64                 string age = object.get("age").getasstring();
65                 
66                 //获取节点存储的json对象
67                 jsonobject asjsonobject = object.getasjsonobject("msg");
68                 jsonelement jsonelement2 = asjsonobject.get("a");//获取对象中的a节点
69                 string a = jsonelement2.getasstring();//获取a节点的值
70                 
71                 //获取对象中的b节点
72                 jsonelement jsonelement3 = asjsonobject.get("b");
73                 string b = jsonelement3.getasstring();//获取b节点的值
74                 
75                 gson gson = new gson();
76                 //获取节点存储的json对象
77                 jsonarray jsonarray = object.getasjsonarray("core");
78                 //遍历jsonarray对象
79                 iterator it = jsonarray.iterator();
80                 while(it.hasnext()){
81                     jsonelement e = (jsonelement)it.next();
82                     //jsonelement转换为javabean对象
83                     student jbdemo = gson.fromjson(e, student.class);
84                     system.out.println(jbdemo.getname() + "-" + jbdemo.getage());  //zhangsan-25  lisi-26
85                 }
86         } catch (jsonioexception e) {
87             e.printstacktrace();
88         } catch (jsonsyntaxexception e) {
89             e.printstacktrace();
90         } catch (filenotfoundexception e) {
91             e.printstacktrace();
92         }
93     }
94 }
 1 import com.google.gson.gson;
 2 
 3 public class jsonanalysis2 {
 4     public static void main(string[] args) {
 5         /**
 6          * gson提供的方法:
 7          *         fromjson(string json, class<t> classoft) 
 8          *         fromjson(jsonelement json, class<t> classoft) 
 9          *     解析json字符串或者jsonelement成指定的对象
10          */
11         string jsondata = "{'name':'john', 'age':20}";
12         gson gson = new gson();
13         student stu = gson.fromjson(jsondata,student.class);
14         system.out.println(stu.getname() + "-" + stu.getage());
15     }
16 }
 1 import com.google.gson.gson;
 2 
 3 public class jsonanalysis3 {
 4     public static void main(string[] args) {
 5         gson gson = new gson();
 6         //解析基本类型数据
 7         int i = gson.fromjson("1", int.class);  
 8         double d = gson.fromjson("\"1.11\"", double.class); 
 9         double d2 = gson.fromjson("1.11", double.class);
10         boolean b = gson.fromjson("true", boolean.class); 
11         string s = gson.fromjson("str", string.class);
12         
13         system.out.println(i);    // 1
14         system.out.println(d);    // 1.11 
15         system.out.println(d2);    // 1.11  
16         system.out.println(b);    // true 
17         system.out.println(s);    // str
18     }
19 }
 1 import com.google.gson.gson;
 2 
 3 public class jsonanalysis4 {
 4     public static void main(string[] args) {
 5         gson gson = new gson();
 6         /**
 7          * tojson(object src) 返回一个字符串。    对象转成json字符串
 8          */
 9         gson gson1 = new gson();  
10         string s1= gson1.tojson(1);  
11         string s2= gson1.tojson(false); 
12         string s3= gson1.tojson("str"); 
13         
14         system.out.println(s1);// 1
15         system.out.println(s2);// false 
16         system.out.println(s3);//"str" 
17     }
18 }
 1 import com.google.gson.gson;
 2 
 3 public class jsonanalysis5 {
 4     public static void main(string[] args) {
 5         gson gson = new gson();
 6         /**
 7          * 字符串数组转成json字符串,然后将json字符串转成字符串数组
 8          */
 9         string jsonss = "[aa,bb,cc]";
10         //将json字符串转成对应的字符串类型的数组
11         string[] str = gson.fromjson(jsonss, string[].class);  
12         for (string st:str) {  
13              system.out.println(st);//遍历得到数组中的元素
14         }  
15     }
16 }
 1 import java.util.arraylist;
 2 import java.util.list;
 3 
 4 import com.google.gson.gson;
 5 import com.google.gson.reflect.typetoken;
 6 /**
 7  * 解析list
 8  */
 9 public class jsonanalysis6 {
10     public static void main(string[] args) {
11         gson gson = new gson();
12         //自己创建json字符串
13         list<string> list = new arraylist<string>();
14         list.add("a");
15         list.add("b");
16         string json = gson.tojson(list);//将list转成json格式的字符串
17         
18         //将json字符串转成对应的字符串类型的数组
19         list<string> strlist = gson.fromjson(json, new typetoken<list<string>>() {}.gettype());  
20         for (string st:strlist) {  
21              system.out.println(st);//遍历得到数组中的元素
22         }  
23     }
24 }

 

gson2

 

 1 public class user {
 2     private string name;
 3     private int age;
 4 
 5     // @serializedname("email_address") // test5()使用
 6     // @serializedname(value="emailaddress",alternate={"email","email_address"})//test6()使用
 7     private string emailaddress;
 8     public user() {}
 9     public user(string name, int age) {
10         this.name = name;
11         this.age = age;
12     }
13     public user(string name, int age, string emailaddress) {
14         this.name = name;
15         this.age = age;
16         this.emailaddress = emailaddress;
17     }
18     //set和get方法
19     public string getname() {
20         return name;
21     }
22     public void setname(string name) {
23         this.name = name;
24     }
25     public int getage() {
26         return age;
27     }
28     public void setage(int age) {
29         this.age = age;
30     }
31     public string getemailaddress() {
32         return emailaddress;
33     }
34     public void setemailaddress(string emailaddress) {
35         this.emailaddress = emailaddress;
36     }
37 }
 1 public class resulter<t> {
 2     public int code;
 3     public string message;
 4     public t data;
 5     public resulter() {}
 6     //set和get方法
 7     public int getcode() {
 8         return code;
 9     }
10 
11     public void setcode(int code) {
12         this.code = code;
13     }
14 
15     public string getmessage() {
16         return message;
17     }
18 
19     public void setmessage(string message) {
20         this.message = message;
21     }
22 
23     public t getdata() {
24         return data;
25     }
26 
27     public void setdata(t data) {
28         this.data = data;
29     }
30 }
  1 import java.util.arraylist;
  2 import java.util.list;
  3 
  4 import com.google.gson.gson;
  5 import com.google.gson.reflect.typetoken;
  6 
  7 public class testgson {
  8     private gson gson = new gson();
  9     /**
 10      * 测试main
 11      */
 12     public static void main(string[] args) {
 13         testgson test = new testgson();
 14         test.test9();
 15     }
 16     /**
 17      * json字符串转基本数据类型(string虽不是基本数据类型,但是是值传递,与基本数据类型处理相似)
 18      */
 19     public void test1() {
 20         int i = gson.fromjson("100", int.class); // 100
 21         double d = gson.fromjson("99.99", double.class); // 99.99
 22         boolean b = gson.fromjson("true", boolean.class); // true
 23         string str = gson.fromjson("string", string.class); // string
 24 
 25         system.out.println(i);
 26         system.out.println(d);
 27         system.out.println(b);
 28         system.out.println(str);
 29     }
 30 
 31     /**
 32      * 基本数据类型转json字符串(string虽不是基本数据类型,但是是值传递,与基本数据类型处理相似)
 33      */
 34     public void test2() {
 35         string jsonnumber = gson.tojson(100); // 100
 36         string jsonboolean = gson.tojson(false); // false
 37         string jsonstring = gson.tojson("string"); // "string"
 38 
 39         system.out.println(jsonnumber);
 40         system.out.println(jsonboolean);
 41         system.out.println(jsonstring);
 42     }
 43 
 44     /**
 45      * java对象转json字符串
 46      */
 47     public void test3() {
 48         user user = new user("zhangsan", 24);
 49         string jsonobject = gson.tojson(user); // {"name":"zhangsan","age":24}
 50         system.out.println(jsonobject);
 51     }
 52 
 53     /**
 54      * json字符串转java对象
 55      */
 56     public void test4() {
 57         string jsonstring = "{name:zhangsan,age:24}";
 58         user user = gson.fromjson(jsonstring, user.class);
 59         system.out.println(user.getname() + " | " + user.getage() + " | " + user.getemailaddress());
 60     }
 61 
 62     /**
 63      * @serializedname()的使用_1
 64      */
 65     public void test5() {
 66         user user = new user("zhangsan", 24, "abc@163.com");
 67         string jsonobject = gson.tojson(user);
 68         // user.emailaddress未加'@serializedname("email_address")'时的转换效果如下:
 69         // {"name":"zhangsan","age":24,"emailaddress":"abc@163.com"}
 70 
 71         // user.emailaddress加了'@serializedname("email_address")'时的转换效果如下:
 72         // {"name":"zhangsan","age":24,"email_address":"abc@163.com"}
 73         system.out.println(jsonobject);
 74     }
 75 
 76     /**
 77      * @serializedname()的使用_2
 78      */
 79     public void test6() {
 80         string json = "{name:zhangsan,age:24,emailaddress:abc_1@example.com,"
 81                 + "email:abc_2@example.com,email_address:abc_3@example.com}";
 82         user user = gson.fromjson(json, user.class);
 83 
 84         system.out.println(user.getemailaddress()); // abc_3@example.com
 85 
 86         // 当上面的三个属性(email_address、email、emailaddress)都中出现任意一个时均可以得到正确的结果。
 87         // 注:当多种情况同时出时,以最后一个出现的值为准。
 88         // 注:alternate需要2.4版本,本次测试的版本不可使用
 89     }
 90 
 91     /**
 92      * json字符串转基本类型数组(string虽不是基本数据类型,但是是值传递,与基本数据类型处理相似)
 93      */
 94     public void test7() {
 95         string jsonarray = "[android,java,php]";
 96         string[] strings = gson.fromjson(jsonarray, string[].class);
 97         system.out.println(strings[1]);
 98     }
 99 
100     /**
101      * typetoken来实现对泛型的支持_1 将string[].class 直接改为 list<string>.class 是行不通的。需要进行泛型擦除。
102      */
103     public void test8() {
104         string jsonarray = "[android,java,php]";
105         list<string> stringlist = gson.fromjson(jsonarray, (new typetoken<list<string>>() {
106         }).gettype());
107         system.out.println(stringlist.get(1));
108     }
109 
110     /**
111      * typetoken来实现对泛型的支持_2
112      */
113     public void test9() {
114         resulter<list<user>> result = new resulter<list<user>>();
115         result.setcode(200);
116         result.setmessage("success");
117         result.setdata(new arraylist<user>() {
118             {
119                 for (int i = 0; i < 2; i++) {
120                     this.add(new user("zhangsan" + i, 25 + i, "abc@163.com"));
121                 }
122             }
123         });
124 
125         // 不使用typetoken无法将user的内容转换出来
126         // fromjson()方法也是一样需要使用typetoken指定要转换成的java对象类型
127         string gsonstr = gson.tojson(result, (new typetoken<resulter<list<user>>>() {
128         }).gettype());
129         system.out.println(gsonstr);
130     }
131 }


 1 import java.util.arraylist;
 2 import java.util.list;
 3 import java.util.map;
 4 
 5 import com.google.gson.gson;
 6 import com.google.gson.jsonarray;
 7 import com.google.gson.jsonelement;
 8 import com.google.gson.jsonparser;
 9 import com.google.gson.reflect.typetoken;
10 
11 /**
12  * @classname: gsonutil
13  * @description: gson解析json工具类
14  */
15 public class gsonutil {
16     private static gson gson = null;
17     
18     static {
19         if (gson == null) {
20             gson = new gson();
21         }
22     }
23 
24     private gsonutil() {}
25 
26     /**
27      * 将object对象 转成json字符串
28      */
29     public static string gsonstring(object object) {
30         string gsonstring = null;
31         if (gson != null) {
32             gsonstring = gson.tojson(object);
33         }
34         return gsonstring;
35     }
36 
37     /**
38      * 将json字符串 转成泛型bean
39      */
40     public static <t> t gsontobean(string gsonstring, class<t> cls) {
41         t t = null;
42         if (gson != null) {
43             t = gson.fromjson(gsonstring, cls);
44         }
45         return t;
46     }
47 
48     /**
49      * json字符串 转成list 泛型在编译期类型被擦除导致报错
50      */
51     public static <t> list<t> gsontolist(string gsonstring, class<t> cls) {
52         list<t> list = null;
53         if (gson != null) {
54             list = gson.fromjson(gsonstring, new typetoken<list<t>>() {
55             }.gettype());
56         }
57         return list;
58     }
59 
60     /**
61      * json字符串 转成list 解决泛型问题
62      */
63     public static <t> list<t> jsontolist(string json, class<t> cls) {
64         gson gson = new gson();
65         list<t> list = new arraylist<t>();
66         jsonarray array = new jsonparser().parse(json).getasjsonarray();
67         for (final jsonelement elem : array) {
68             list.add(gson.fromjson(elem, cls));
69         }
70         return list;
71     }
72 
73     /**
74      * json字符串中有map的 转成list
75      */
76     public static <t> list<map<string, t>> gsontolistmaps(string gsonstring) {
77         list<map<string, t>> list = null;
78         if (gson != null) {
79             list = gson.fromjson(gsonstring, new typetoken<list<map<string, t>>>() {
80             }.gettype());
81         }
82         return list;
83     }
84 
85     /**
86      * json字符串 转成map的
87      */
88     public static <t> map<string, t> gsontomaps(string gsonstring) {
89         map<string, t> map = null;
90         if (gson != null) {
91             map = gson.fromjson(gsonstring, new typetoken<map<string, t>>() {
92             }.gettype());
93         }
94         return map;
95     }
96 }