Java創建和解析Json數據方法(五)——Google Gson包的使用


(五)Google Gson包的使用

1.簡介

Gson包中,使用最多的是Gson類的toJson()和fromJson()方法:
        ①toJson():將java對象轉化為json數據(一般為json格式的字符串)  (序列化)
        ②fromJson():從json數據(json格式字符串)轉為java對象   (反序列化)
也可以使用JsonObject和JsonArray類的無參構造函數創建實例,然后調用add()方法來構造json數據,用法與org.json包和json-lib包差不多,但卻少了一些方法;這里使用Gson包還是推薦使用Gson類的toJson()和fromJson()方法。
Github上的原話:
Gson Goals:
  • Provide simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa
  • Allow pre-existing unmodifiable objects to be converted to and from JSON
  • Extensive support of Java Generics
  • Allow custom representations for objects
  • Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)
Github的地址: https://github.com/google/gson
各個版本的下載地址: http://www.mvnrepository.com/artifact/com.google.code.gson/gson

2.json與簡單數據類型、數組

例子:
 1 package gson;
 2 import com.google.gson.Gson;
 3 public class Test {
 4     public static void main(String[] args) {
 5         Gson gson = new Gson();
 6         // 簡單數據類型 轉為 json
 7         String intStr = gson.toJson(1);
 8         String stringStr = gson.toJson("abcd");
 9         String longStr = gson.toJson(new Long(10));
10         System.out.println(intStr);      // int
11         System.out.println(stringStr);   // String
12         System.out.println(longStr);     // Long
13         // json 轉為 簡單數據類型
14         int id1 = gson.fromJson("1", int.class);
15         Integer id2 = gson.fromJson("1", Integer.class);
16         Boolean boolean1 = gson.fromJson("false", Boolean.class);
17         String str = gson.fromJson("\"abc\"", String.class);
18         System.out.println(id1);
19         System.out.println(id2);
20         System.out.println(boolean1);
21         System.out.println(str);
22 
23         // java array 轉為  json
24         String[] strings = { "abc", "def", "ghi" };
25         int[][] intInt = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
26         String stringStrs = gson.toJson(strings); // String數組轉為json
27         String intIntStr = gson.toJson(intInt);   // 多維數據轉為json
28         System.out.println(stringStrs);
29         System.out.println(intIntStr);
30         //json 轉為  java array
31         String[] strings2 = gson.fromJson(stringStrs, String[].class);
32         int[][] intInt2 = gson.fromJson(intIntStr, int[][].class);
33         for (int i = 0; i < strings2.length; i++) {   //輸出String[]
34             System.out.print(strings2[i] + " ");
35         }
36         System.out.println();
37         for (int i = 0; i < intInt2.length; i++) {    //輸出int[][]
38             for (int j = 0; j < intInt2[i].length; j++) {
39                 System.out.print(intInt2[i][j] + ",");
40             }
41             System.out.print(" ");
42         }
43     }
44 }
輸出結果:

3.json與java集合、Map

例子:
 1 package gson;
 2 import java.lang.reflect.Type;
 3 import java.util.ArrayList;
 4 import java.util.HashMap;
 5 import java.util.List;
 6 import java.util.Map;
 7 import com.google.gson.Gson;
 8 import com.google.gson.reflect.TypeToken;
 9 public class Test {
10     public static void main(String[] args) {
11         Gson gson = new Gson();
12         // Map 轉 json
13         Map<string object=""> map = new HashMap<string object="">();
14         map.put("name", "JTZen9");
15         map.put("age", 21);
16         map.put("sex", "male");
17         String jsonMap = gson.toJson(map);
18         System.out.println(jsonMap);
19         // json 轉 Map
20         Type type = new TypeToken<Map<string object="">>() {}.getType();
21         Map<string object=""> map2 = gson.fromJson(jsonMap, type);
22         System.out.println(map2.get("name") + " " + map2.get("age") + " " + map2.get("sex"));
23 
24         // java集合 轉 json
25         List<object> nameList = new ArrayList</object><object>();
26         nameList.add("JTZen9");
27         nameList.add(map);
28         nameList.add("DSMGYH");
29         String jsonNames = gson.toJson(nameList);
30         System.out.println(jsonNames);
31         // json 轉 java集合
32         type = new TypeToken<List</object><object>>() {}.getType();
33         List</object><object> list = gson.fromJson(jsonNames, type);
34         for (int i = 0; i < list.size(); i++) {
35             System.out.print(list.get(i) + "   ");
36         }
37     }
38 }
輸出結果:

4.json與java beans

        沿用上幾篇筆記的Student類:name、age、sex字段以及getter和setter方法。
例子:
 1 package gson;
 2 import com.google.gson.Gson;
 3 public class Test {
 4     public static void main(String[] args) {
 5         Student student = new Student();
 6         student.setName("JTZen9");
 7         student.setAge(21);
 8         student.setSex("male");
 9         Gson gson = new Gson();
10         // java bean 轉 json
11         String beanStr = gson.toJson(student);
12         System.out.println(beanStr);
13         // json 轉 java bean 
14         Student student2 = gson.fromJson(beanStr, Student.class);
15         System.out.println(student2.getName() + "  " + student2.getAge() + "  " + student2.getSex());
16         
17         // 轉為json數據時,只會轉換屬性值的字段
18         Student stu = new Student();
19         stu.setName("JTZen9");
20         stu.setAge(21);
21         String test = gson.toJson(stu);
22         System.out.println(test);  //沒有sex字段
23     }
24 }
輸出結果:
json-lib包中,JSONObject.fromObject()構造的json數據,全部的字段都包含,沒有賦值的都為空;
Gson包的toJson()方法和org.json包的new JSONObject()方法,轉換java bean為json數據時,只會轉換有賦值的字段。
 

5.解析json數據

json數據如下:
 1 {
 2     "roomname":[
 3         {
 4             "PCnum":0,
 5             "num":2,
 6             "name":"biubiubiu",
 7             "time":"十二月 18, 2015"
 8         },
 9         {
10             "PCnum":0,
11             "num":1,
12             "name":"jtz",
13             "time":"十二月 19, 2015"
14         },
15         {
16             "PCnum":0,
17             "num":1,
18             "name":"jtzeng",
19             "time":"十二月 19, 2015"
20         }
21         
22     ]
23 }
使用JsonObject和JsonArray的配合來使用也是可以解析的,但是這樣解析起來就比較麻煩,當json數據又多又復雜時候更是麻煩,所以這里有一種簡單的方法,首先定義一個對應json數據字段的java類:
 1 package gson;
 2 import java.util.List;
 3 public class JsonBean {
 4     public List<roomdata> roomname;
 5     public class RoomData {
 6         public int PCnum;
 7         public int num;
 8         public String name;
 9         public String time;
10     }
11 }
然后,測試如下:
 1 package gson;
 2 import java.lang.reflect.Type;
 3 import com.google.gson.Gson;
 4 import com.google.gson.reflect.TypeToken;
 5 public class Test {
 6     public static void main(String[] args) {
 7         //要解析json數據
 8         String json = "{'roomname':[{'PCnum':0,'num':2,'name':'biubiubiu','time':'Dec 22, 2015'},"
 9                 + "{'PCnum':0,'num':1,'name':'jtz','time':'Dec 18, 2015'},"
10                 + "{'PCnum':0,'num':0,'name':'JTZen9','time':'Dec 22, 2015'}]}";
11         Gson gson = new Gson();
12         Type type = new TypeToken<jsonbean>(){}.getType();
13         JsonBean jsonBean = gson.fromJson(json, type);
14         System.out.println(jsonBean.roomname.size());
15         for (int i = 0; i < jsonBean.roomname.size(); i++) {
16             System.out.println(jsonBean.roomname.get(i).name + " 、 "
17                     + jsonBean.roomname.get(i).PCnum + " 、 "
18                     + jsonBean.roomname.get(i).num + " 、 "
19                     + jsonBean.roomname.get(i).time);
20         }
21     }
22 }
輸出的結果如下:
需要注意的是:定義的類中,屬性字段名必須跟json數據的key字段名一樣。

6.結束語

        還有很多的方法沒有嘗試,往后慢慢積累。
        org.json包、json-lib包、Gson包,終於搞清楚了些,做課程作業時糊里糊塗的。相比之下,感覺Gson挺好用的,往后深入探究探究Gson。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM