Google Gson 使用简介

来源:互联网 发布:java调用其他类方法 编辑:程序博客网 时间:2024/06/05 05:48

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



如何将数组转化为 json 串?


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

复制代码
import com.google.gson.Gson;public class ArrayToJson {    public static void main(String[] args) {        int[] numbers = {1, 1, 2, 3, 5, 8, 13};        String[] days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};        //        // Create a new instance of Gson        //        Gson gson = new Gson();        //        // Convert numbers array into JSON string.        //        String numbersJson = gson.toJson(numbers);        //        // Convert strings array into JSON string        //        String daysJson = gson.toJson(days);        System.out.println("numbersJson = " + numbersJson);        System.out.println("daysJson = " + daysJson);        //        // Convert from JSON string to a primitive array of int.        //        int[] fibonacci = gson.fromJson(numbersJson, int[].class);        for (int i = 0; i < fibonacci.length; i++) {            System.out.print(fibonacci[i] + " ");        }        System.out.println("");        //        // Convert from JSON string to a string array.        //        String[] weekDays = gson.fromJson(daysJson, String[].class);        for (int i = 0; i < weekDays.length; i++) {            System.out.print(weekDays[i] + " ");        }        System.out.println("");        //        // Converting multidimensional array into JSON        //        int[][] data = {{1, 2, 3}, {3, 4, 5}, {4, 5, 6}};        String json = gson.toJson(data);        System.out.println("Data = " + json);        //        // Convert JSON string into multidimensional array of int.        //        int[][] dataMap = gson.fromJson(json, int[][].class);        for (int i = 0; i < data.length; i++) {            for (int j = 0; j < data[i].length; j++) {                System.out.print(data[i][j] + " ");            }            System.out.println("");        }    }}
复制代码

以下是输出结果:

复制代码
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 规则的字符串。

复制代码
import java.util.Date;public class Student {    private String name;    private String address;    private Date dateOfBirth;    public Student() {    }    public Student(String name, String address, Date dateOfBirth) {        this.name = name;        this.address = address;        this.dateOfBirth = dateOfBirth;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getAddress() {        return address;    }    public void setAddress(String address) {        this.address = address;    }    public Date getDateOfBirth() {        return dateOfBirth;    }    public void setDateOfBirth(Date dateOfBirth) {        this.dateOfBirth = dateOfBirth;    }}
复制代码
复制代码
import com.google.gson.Gson;import com.google.gson.reflect.TypeToken;import java.lang.reflect.Type;import java.util.ArrayList;import java.util.Date;import java.util.List;public class CollectionToJson {    public static void main(String[] args) {        //        // Converts a collection of string object into JSON string.        //        List<String> names = new ArrayList<String>();        names.add("Alice");        names.add("Bob");        names.add("Carol");        names.add("Mallory");        Gson gson = new Gson();        String jsonNames = gson.toJson(names);        System.out.println("jsonNames = " + jsonNames);        //        // Converts a collection Student object into JSON string        //        Student a = new Student("Alice", "Apple St", new Date(2000, 10, 1));        Student b = new Student("Bob", "Banana St", null);        Student c = new Student("Carol", "Grape St", new Date(2000, 5, 21));        Student d = new Student("Mallory", "Mango St", null);        List<Student> students = new ArrayList<Student>();        students.add(a);        students.add(b);        students.add(c);        students.add(d);        gson = new Gson();        String jsonStudents = gson.toJson(students);        System.out.println("jsonStudents = " + jsonStudents);        //        // Converts JSON string into a collection of Student object.        //        Type type = new TypeToken<List<Student>>(){}.getType();        List<Student> studentList = gson.fromJson(jsonStudents, type);        for (Student student : studentList) {            System.out.println("student.getName() = " + student.getName());        }    }}
复制代码

以下是输出结果:

复制代码
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() = Alicestudent.getName() = Bobstudent.getName() = Carolstudent.getName() = Mallory
复制代码

 

如何将Map转化为 json 串?

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

复制代码
import com.google.gson.Gson;import com.google.gson.reflect.TypeToken;import java.lang.reflect.Type;import java.util.HashMap;import java.util.Map;public class MapToJson {    public static void main(String[] args) {        Map<String, String> colours = new HashMap<String, String>();        colours.put("BLACK", "#000000");        colours.put("RED", "#FF0000");        colours.put("GREEN", "#008000");        colours.put("BLUE", "#0000FF");        colours.put("YELLOW", "#FFFF00");        colours.put("WHITE", "#FFFFFF");        //        // Convert a Map into JSON string.        //        Gson gson = new Gson();        String json = gson.toJson(colours);        System.out.println("json = " + json);        //        // Convert JSON string back to Map.        //        Type type = new TypeToken<Map<String, String>>(){}.getType();        Map<String, String> map = gson.fromJson(json, type);        for (String key : map.keySet()) {            System.out.println("map.get = " + map.get(key));        }    }}
复制代码

以下是输出结果:

复制代码
json = {"WHITE":"#FFFFFF","BLUE":"#0000FF","YELLOW":"#FFFF00","GREEN":"#008000","BLACK":"#000000","RED":"#FF0000"}map.get = #FFFFFFmap.get = #0000FFmap.get = #FFFF00map.get = #008000map.get = #000000map.get = #FF0000
复制代码

 

如何将对象转换为 json 串?

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

复制代码
import com.google.gson.Gson;import java.util.Calendar;public class StudentToJson {    public static void main(String[] args) {        Calendar dob = Calendar.getInstance();        dob.set(2000, 1, 1, 0, 0, 0);        Student student = new Student("Duke", "Menlo Park", dob.getTime());        Gson gson = new Gson();        String json = gson.toJson(student);        System.out.println("json = " + json);    }}
复制代码
复制代码
import java.util.Date;public class Student {    private String name;    private String address;    private Date dateOfBirth;    public Student() {    }    public Student(String name, String address, Date dateOfBirth) {        this.name = name;        this.address = address;        this.dateOfBirth = dateOfBirth;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getAddress() {        return address;    }    public void setAddress(String address) {        this.address = address;    }    public Date getDateOfBirth() {        return dateOfBirth;    }    public void setDateOfBirth(Date dateOfBirth) {        this.dateOfBirth = dateOfBirth;    }}
复制代码

以下是输出结果:

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

 

如何将 json 串转换为对象?

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

复制代码
import com.google.gson.Gson;public class JsonToStudent {    public static void main(String[] args) {        String json = "{\"name\":\"Duke\",\"address\":\"Menlo Park\",\"dateOfBirth\":\"Feb 1, 2000 12:00:00 AM\"}";        Gson gson = new Gson();        Student student = gson.fromJson(json, Student.class);        System.out.println("student.getName()        = " + student.getName());        System.out.println("student.getAddress()     = " + student.getAddress());        System.out.println("student.getDateOfBirth() = " + student.getDateOfBirth());    }}
复制代码

以下是输出结果:

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

 

如何处理对象的字段?

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

复制代码
import com.google.gson.Gson;import java.util.Calendar;public class GsonFieldExample {    public static void main(String[] args) {        Calendar dob = Calendar.getInstance();        dob.set(1980, 10, 11);        People people = new People("John", "350 Banana St.", dob.getTime());        people.setSecret("This is a secret!");        Gson gson = new Gson();        String json = gson.toJson(people);        System.out.println("json = " + json);    }}
复制代码
复制代码
import java.util.Date;public class People {    private String name;    private String address;    private Date dateOfBirth;    private Integer age;    private transient String secret;    public People(String name, String address, Date dateOfBirth) {        this.name = name;        this.address = address;        this.dateOfBirth = dateOfBirth;    }    public String getSecret() {        return secret;    }    public void setSecret(String secret) {        this.secret = secret;    }}
复制代码

 以下是输出结果:

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

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 党员培养期不足一年怎么办 出生证明日期错了怎么办 毕业生登记表写错了怎么办 高等学校毕业生登记表写错了怎么办 眼睛里迷了东西怎么办 眼睛迷了怎么办小绝招 isf货物离港申报怎么办 非农户口没住房怎么办 在工厂上班很累怎么办 退货运费太贵了怎么办 悬肘写字手抖怎么办 护士成绩合格证明丢了怎么办 找工作真难找好烦怎么办 大夫说身体不适合怀孕有了怎么办 不知道要做什么工作怎么办 红米note4x闪退怎么办 魅蓝note3闪退怎么办 红米note2闪退怎么办 安卓不支持计步怎么办 银行多扣了钱怎么办 网络配置器没了怎么办 班里丢钱了应该怎么办 初级会计考过了怎么办 教师职称证丢了怎么办 会计初级证丢了怎么办 工作遭同事不满否认质疑怎么办 单位领导不让进收入财务怎么办 事业单位50岁不愿退休的怎么办 回美国i20丢了怎么办 i20忘签字美国入境怎么办 社保基数报错了怎么办 公司合同没给我怎么办 给客户报错价格怎么办 给客户报价低了怎么办 报价失误报低了怎么办 期望薪资说低了怎么办 期望薪资说高了怎么办 面试工资说低了怎么办 期望薪资谈低了怎么办 请年假公司不批怎么办 期望工资填低了怎么办