Google Gson 使用简介

原文:http://www.cnblogs.com/haippy/archive/2012/05/20/2509329.html

一、如何将数组转化为 json 串?

下面的例子中我们示例如何将一个数据转换成 json 串,并使用 Gson.toJson() 方法将数组序列化为 JSON,以及Gson.fromJson() 方法将 JSON 串反序列化为 java 数组。

 1 import com.google.gson.Gson;
 2 
 3 public class ArrayToJson {
 4     public static void main(String[] args) {
 5         int[] numbers = {1, 1, 2, 3, 5, 8, 13};
 6         String[] days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
 7 
 8         //
 9         // Create a new instance of Gson
10         //
11         Gson gson = new Gson();
12 
13         //
14         // Convert numbers array into JSON string.
15         //
16         String numbersJson = gson.toJson(numbers);
17 
18         //
19         // Convert strings array into JSON string
20         //
21         String daysJson = gson.toJson(days);
22         System.out.println("numbersJson = " + numbersJson);
23         System.out.println("daysJson = " + daysJson);
24 
25         //
26         // Convert from JSON string to a primitive array of int.
27         //
28         int[] fibonacci = gson.fromJson(numbersJson, int[].class);
29         for (int i = 0; i < fibonacci.length; i++) {
30             System.out.print(fibonacci[i] + " ");
31         }
32         System.out.println("");
33 
34         //
35         // Convert from JSON string to a string array.
36         //
37         String[] weekDays = gson.fromJson(daysJson, String[].class);
38         for (int i = 0; i < weekDays.length; i++) {
39             System.out.print(weekDays[i] + " ");
40         }
41         System.out.println("");
42 
43         //
44         // Converting multidimensional array into JSON
45         //
46         int[][] data = {{1, 2, 3}, {3, 4, 5}, {4, 5, 6}};
47         String json = gson.toJson(data);
48         System.out.println("Data = " + json);
49 
50         //
51         // Convert JSON string into multidimensional array of int.
52         //
53         int[][] dataMap = gson.fromJson(json, int[][].class);
54         for (int i = 0; i < data.length; i++) {
55             for (int j = 0; j < data[i].length; j++) {
56                 System.out.print(data[i][j] + " ");
57             }
58             System.out.println("");
59         }
60     }
61 }

以下是输出结果:

numbersJson = [1,1,2,3,5,8,13]
daysJson = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
1 1 2 3 5 8 13 
Sun Mon Tue Wed Thu Fri Sat 
Data = [[1,2,3],[3,4,5],[4,5,6]]
1 2 3 
3 4 5

二、如何将集合转化为 json 串?

下面的例子中我们示例如何将Java集合转换为符合 json 规则的字符串。

 1 import java.util.Date;
 2 
 3 public class Student {
 4     private String name;
 5     private String address;
 6     private Date dateOfBirth;
 7 
 8     public Student() {
 9     }
10 
11     public Student(String name, String address, Date dateOfBirth) {
12         this.name = name;
13         this.address = address;
14         this.dateOfBirth = dateOfBirth;
15     }
16 }
 1 import com.google.gson.Gson;
 2 import com.google.gson.reflect.TypeToken;
 3 
 4 import java.lang.reflect.Type;
 5 import java.util.ArrayList;
 6 import java.util.Date;
 7 import java.util.List;
 8 
 9 public class CollectionToJson {
10     public static void main(String[] args) {
11         //
12         // Converts a collection of string object into JSON string.
13         //
14         List<String> names = new ArrayList<String>();
15         names.add("Alice");
16         names.add("Bob");
17         names.add("Carol");
18         names.add("Mallory");
19 
20         Gson gson = new Gson();
21         String jsonNames = gson.toJson(names);
22         System.out.println("jsonNames = " + jsonNames);
23 
24         //
25         // Converts a collection Student object into JSON string
26         //
27         Student a = new Student("Alice", "Apple St", new Date(2000, 10, 1));
28         Student b = new Student("Bob", "Banana St", null);
29         Student c = new Student("Carol", "Grape St", new Date(2000, 5, 21));
30         Student d = new Student("Mallory", "Mango St", null);
31 
32         List<Student> students = new ArrayList<Student>();
33         students.add(a);
34         students.add(b);
35         students.add(c);
36         students.add(d);
37 
38         gson = new Gson();
39         String jsonStudents = gson.toJson(students);
40         System.out.println("jsonStudents = " + jsonStudents);
41 
42         //
43         // Converts JSON string into a collection of Student object.
44         //
45         Type type = new TypeToken<List<Student>>(){}.getType();
46         List<Student> studentList = gson.fromJson(jsonStudents, type);
47 
48         for (Student student : studentList) {
49             System.out.println("student.getName() = " + student.getName());
50         }
51     }
52 }

以下是输出结果:

jsonNames = ["Alice","Bob","Carol","Mallory"]
jsonStudents = [{"name":"Alice","address":"Apple St","dateOfBirth":"Nov 1, 3900 12:00:00 AM"},{"name":"Bob","address":"Banana St"},{"name":"Carol","address":"Grape St","dateOfBirth":"Jun 21, 3900 12:00:00 AM"},{"name":"Mallory","address":"Mango St"}]
student.getName() = Alice
student.getName() = Bob
student.getName() = Carol
student.getName() = Mallory

三、如何将Map转化为 json 串?

下面的例子中我们示例如何将java.util.Map转化成 json 串,然后再将 json 串转换为java.util.Map

 1 import com.google.gson.Gson;
 2 import com.google.gson.reflect.TypeToken;
 3 
 4 import java.lang.reflect.Type;
 5 import java.util.HashMap;
 6 import java.util.Map;
 7 
 8 public class MapToJson {
 9     public static void main(String[] args) {
10         Map<String, String> colours = new HashMap<String, String>();
11         colours.put("BLACK", "#000000");
12         colours.put("RED", "#FF0000");
13         colours.put("GREEN", "#008000");
14         colours.put("BLUE", "#0000FF");
15         colours.put("YELLOW", "#FFFF00");
16         colours.put("WHITE", "#FFFFFF");
17 
18         //
19         // Convert a Map into JSON string.
20         //
21         Gson gson = new Gson();
22         String json = gson.toJson(colours);
23         System.out.println("json = " + json);
24 
25         //
26         // Convert JSON string back to Map.
27         //
28         Type type = new TypeToken<Map<String, String>>(){}.getType();
29         Map<String, String> map = gson.fromJson(json, type);
30         for (String key : map.keySet()) {
31             System.out.println("map.get = " + map.get(key));
32         }
33     }
34 }

以下是输出结果:

json = {"WHITE":"#FFFFFF","BLUE":"#0000FF","YELLOW":"#FFFF00","GREEN":"#008000","BLACK":"#000000","RED":"#FF0000"}
map.get = #FFFFFF
map.get = #0000FF
map.get = #FFFF00
map.get = #008000
map.get = #000000
map.get = #FF0000

四、如何将对象转换为 json 串?

下面的例子中我们示例如何将一个 Student 对象转换成 json 串,实际操作中我们也可以将任意的 Java 类转换为 json 串,并且实施起来也非常简单,你仅仅需要创建一个 Gson 实例,然后传递将被转化为 json 串的对象,并调用该实例的 toJson 方法即可。

 1 import com.google.gson.Gson;
 2 
 3 import java.util.Calendar;
 4 
 5 public class StudentToJson {
 6     public static void main(String[] args) {
 7         Calendar dob = Calendar.getInstance();
 8         dob.set(2000, 1, 1, 0, 0, 0);
 9         Student student = new Student("Duke", "Menlo Park", dob.getTime());
10 
11         Gson gson = new Gson();
12         String json = gson.toJson(student);
13         System.out.println("json = " + json);
14     }
15 }

以下是输出结果:

json = {"name":"Duke","address":"Menlo Park","dateOfBirth":"Feb 1, 2000 12:00:00 AM"}

五、如何将 json 串转换为对象?

下面的例子中我们示例如何 json 串转化成 Java对象。

 1 import com.google.gson.Gson;
 2 
 3 public class JsonToStudent {
 4     public static void main(String[] args) {
 5         String json = "{\"name\":\"Duke\",\"address\":\"Menlo Park\",\"dateOfBirth\":\"Feb 1, 2000 12:00:00 AM\"}";
 6 
 7         Gson gson = new Gson();
 8         Student student = gson.fromJson(json, Student.class);
 9 
10         System.out.println("student.getName()        = " + student.getName());
11         System.out.println("student.getAddress()     = " + student.getAddress());
12         System.out.println("student.getDateOfBirth() = " + student.getDateOfBirth());
13     }
14 }

以下是输出结果:

student.getName()        = Duke
student.getAddress()     = Menlo Park
student.getDateOfBirth() = Tue Feb 01 00:00:00 CST 2000

六、如何处理对象的字段?

下面的例子中我们示例如何利用Gson处理一个对象的某一字段。

 1 import com.google.gson.Gson;
 2 
 3 import java.util.Calendar;
 4 
 5 public class GsonFieldExample {
 6     public static void main(String[] args) {
 7         Calendar dob = Calendar.getInstance();
 8         dob.set(1980, 10, 11);
 9         People people = new People("John", "350 Banana St.", dob.getTime());
10         people.setSecret("This is a secret!");
11 
12         Gson gson = new Gson();
13         String json = gson.toJson(people);
14         System.out.println("json = " + json);
15     }
16 }
 1 public class People {
 2     private String name;
 3     private String address;
 4     private Date dateOfBirth;
 5     private Integer age;
 6     private transient String secret;
 7 
 8     public People(String name, String address, Date dateOfBirth) {
 9         this.name = name;
10         this.address = address;
11         this.dateOfBirth = dateOfBirth;
12     }
13 
14     public String getSecret() {
15         return secret;
16     }
17 
18     public void setSecret(String secret) {
19         this.secret = secret;
20     }
21 }

以下是输出结果:

json = {"name":"John","address":"350 Banana St.","dateOfBirth":"Nov 11, 1980 8:47:04 AM"}

 

posted @ 2015-09-16 14:09  季樊  阅读(241)  评论(0编辑  收藏  举报