1 package gson;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6 import com.google.gson.Gson;
7 import com.google.gson.GsonBuilder;
8 import com.google.gson.reflect.TypeToken;
9
10 /**
11 * Gson:解析json工具基础用法加高级进阶
12 *
13 * ClassName: GsonUtils
14 * TypeToken:只是为了提取泛型的类型而已
15 * 控制缩进:final Gson gson = new GsonBuilder().setVersion(1.1).setPrettyPrinting().create();
16 * 调用setPrettyPrinting方法,改变gson对象的默认行
17 *
18 * @Description: TODO
19 * @author liuhl
20 * @date 2018年3月1日
21 */
22 public class GsonUtils {
23
24 public static final Gson gson = new GsonBuilder().create();
25
26 /* 基本数据类型的解析 */
27 int number = gson.fromJson("1", int.class);
28 double money = gson.fromJson("800.25", double.class);
29 boolean bool = gson.fromJson("true", boolean.class);
30 String str = gson.fromJson("kele", String.class);
31 /* 基本数据类型的解析 */
32
33 /* 基本数据类型的生成 */
34 String istr = gson.toJson(1);
35 String dstr = gson.toJson(9000.88);
36 String bstr = gson.toJson("true");
37 String str2 = gson.toJson("baihe");
38 /* 基本数据类型的生成 */
39
40 /* 实体类的解析与生成 */
41 Ticket ticket = new Ticket("2002", 33333.33, "1.1.230010", true);
42 String json = gson.toJson(ticket);
43 Ticket tick = gson.fromJson(json, Ticket.class);
44 /* 实体类的解析与生成 */
45
46 /* json转为数组 */
47 String jsonss = "['aa','bb','cc','dd']";
48 String[] ss = gson.fromJson(jsonss, String[].class);
49 String jsonsss = gson.toJson(ss);
50 /* json转为数组 */
51
52 /* json <----> List */
53 String ljson = "['username','age','data']";
54 List<String> list = gson.fromJson(ljson, new TypeToken<List<String>>() {}.getType());
55 String listjson = gson.toJson(list);
56 /* json <----> List */
57
58 /* 泛型的使用 */
59 User<Ticket> user = new User<Ticket>("10001", 25, ticket);
60 String userjson = gson.toJson(user);
61 User<Ticket> userticket = gson.fromJson(userjson, new TypeToken<User<Ticket>>() {}.getType());
62 /* 泛型的使用 */
63
64
65
66
67 public static void main(String[] args) {
68 /*扩展*/
69 List<Ticket> ticList = new ArrayList<>();
70 ticList.add(new Ticket("3003", 444.444, "2.2.30003", false));
71 ticList.add(new Ticket("4004", 444.444, "4.4.30003", true));
72 ticList.add(new Ticket("5005", 444.444, "5.5.30003", false));
73 ticList.add(new Ticket("6006", 444.444, "6.6.30003", true));
74 ticList.add(new Ticket("7007", 444.444, "7.7.30003", false));
75
76 User<List<Ticket>> userlistTic = new User<List<Ticket>>("lhl", 28, ticList);
77 String json = gson.toJson(userlistTic);
78 User<List<Ticket>> ticuserList = gson.fromJson(json, new TypeToken<User<List<Ticket>>>(){}.getType());
79 /*扩展*/
80 System.out.println(ticuserList.age);
81 System.out.println(ticuserList.usercode);
82 for (Ticket ticket : ticuserList.data) {
83 System.out.println(ticket.dealCode);
84 System.out.println(ticket.instnCode);
85 System.out.println(ticket.dealFlag);
86 System.out.println(ticket.money);
87 }
88 }
89 }