Google Gson的使用方法,实现Json结构的相互转换
在Java开发中,有时需要保存一个数据结构成字符串,可能你会考虑用Json,但是当Json字符串转换成Java对象时,转换成的是JsonObject,并不是你想要的Class类型的对象,操作起来就很不是愉悦,下面说的就可以解决了这种问题。
首先,需要把Google的Gson的Jar包导入到项目中,这个导入包的简单步骤就不展示了
现在,我先自定义一个Class类
[java]
1. public class Student {
2. public int id;
3. public String nickName;
4. public int age;
5. public ArrayList<String> books;
6. public HashMap<String, String> booksMap;
7. }
案例一,案例二,案例三都是把Java的Class对象使用Gson转换成Json的字符串
案例一:
仅包含基本数据类型的数据结构
[java]
1. Gson gson = new Gson();
2. new Student();
3. 1;
4. "乔晓松";
5. 22;
6. "965266509@qq.com";
7. "MainActivity", gson.toJson(student));
输出结果是 :
[java]
1. {"email":"965266509@qq.com","nickName":"乔晓松","id":1,"age":22}
案例二:
除了基本数据类型还包含了List集合
[java]
1. Gson gson = new Gson();
2. new Student();
3. 1;
4. "乔晓松";
5. 22;
6. "965266509@qq.com";
7. new ArrayList<String>();
8. "数学");
9. "语文");
10. "英语");
11. "物理");
12. "化学");
13. "生物");
14. student.books = books;
15. "MainActivity", gson.toJson(student));
输出结果是 :
[html]
1. {"books":["数学","语文","英语","物理","化学","生物"],"email":"965266509@qq.com","nickName":"乔晓松","id":1,"age":22}
案例三:
除了基本数据类型还包含了List和Map集合
[java]
1. Gson gson = new Gson();
2. new Student();
3. 1;
4. "乔晓松";
5. 22;
6. "965266509@qq.com";
7. new ArrayList<String>();
8. "数学");
9. "语文");
10. "英语");
11. "物理");
12. "化学");
13. "生物");
14. student.books = books;
15. new HashMap<String, String>();
16. "1", "数学");
17. "2", "语文");
18. "3", "英语");
19. "4", "物理");
20. "5", "化学");
21. "6", "生物");
22. student.booksMap = booksMap;
23. "MainActivity", gson.toJson(student));
输出结果是 :
[java]
1. {"books":["数学","语文","英语","物理","化学","生物"],"booksMap":{"3":"英语","2":"语文","1":"数学","6":"生物","5":"化学","4":"物理"},"email":"965266509@qq.com","nickName":"乔晓松","id":1,"age":22}
案例四:
把案例三输出的字符串使用Gson转换成Student对象
[java]
1. Gson gson = new Gson();
2. new Student();
3. 1;
4. "乔晓松";
5. 22;
6. "965266509@qq.com";
7. new ArrayList<String>();
8. "数学");
9. "语文");
10. "英语");
11. "物理");
12. "化学");
13. "生物");
14. student.books = books;
15. new HashMap<String, String>();
16. "1", "数学");
17. "2", "语文");
18. "3", "英语");
19. "4", "物理");
20. "5", "化学");
21. "6", "生物");
22. student.booksMap = booksMap;
23. String result = gson.toJson(student);
24.
25. class);
26.
27. "MainActivity", "id:" + studentG.id);
28. "MainActivity", "nickName:" + studentG.nickName);
29. "MainActivity", "age:" + studentG.age);
30. "MainActivity", "email:" + studentG.email);
31. "MainActivity", "books size:" + studentG.books.size());
32. "MainActivity", "booksMap size:" + studentG.booksMap.size());
需要注意的是:
1、因为json转为类时候有的数据有或没有,因此最好是javabean的类,类的子类都可以设为共有的。
2、当从服务器得到的json数据非常复杂的时候,可以用hijson工具解析出类的架构,然后来构建类。