Gson简要使用笔记









Gson简要使用笔记

哇,原来我已经潜水2年多了,还是需要养成习惯写写东西啊。

最近在做一个java web service项目,需要用到jason,本人对java不是特别精通,于是开始搜索一些java平台的json类库。

发现了google的gson,因为之前对于protocolbuf有一些了解,带着一些好奇心,我开始使用了gson。

经过比较,gson和其他现有java json类库最大的不同时gson需要序列化得实体类不需要使用annotation来标识需要序列化得字段,同时gson又可以通过使用annotation来灵活配置需要序列化的字段。

下面是一个简单的例子:

复制代码
      
      
      
      
public class Person {

private String name;
private int age;

/**
*
@return the name
*/
public String getName() {
return name;
}

/**
*
@param name the name to set
*/
public void setName(String name) {
this .name = name;
}

/**
*
@return the age
*/
public int getAge() {
return age;
}

/**
*
@param age the age to set
*/
public void setAge( int age) {
this .age = age;
}

@Override
public String toString()
{
return name + " : " + age;
}
}
复制代码

实体很简单,两个字段,当然实体中的字段也可以是List或者Set类型的。

复制代码
      
      
      
      
Gson gson = new Gson();
List
< Person > persons = new ArrayList < Person > ();
for ( int i = 0 ; i < 10 ; i ++ ) {
Person p
= new Person();
p.setName(
" name " + i);
p.setAge(i
* 5 );
persons.add(p);
}
String str
= gson.toJson(persons);
复制代码

上面的代码重点是Gson对象,它提供了toJason()方法将对象转换成Json字符串,上面代码的str对象值为:

[{"name":"name0","age":0},{"name":"name1","age":5},{"name":"name2","age":10},{"name":"name3","age":15},{"name":"name4","age":20},{"name":"name5","age":25},{"name":"name6","age":30},{"name":"name7","age":35},{"name":"name8","age":40},{"name":"name9","age":45}]

很标准的json数据,很简单吧,呵呵。

下面来看看gson的反序列化,Gson提供了fromJson()方法来实现从Json相关对象到java实体的方法。

在日常应用中,我们一般都会碰到两种情况,转成单一实体对象和转换成对象列表或者其他结构。

先来看第一种:

比如json字符串为:[{"name":"name0","age":0}]

代码:

     
     
     
     
Person person = gson.fromJson(str, Person. class );

提供两个参数,分别是json字符串以及需要转换对象的类型。

第二种,转换成列表类型:

代码:

     
     
     
     
List < Person > ps = gson.fromJson(str, new TypeToken < List < Person >> (){}.getType());
for ( int i = 0 ; i < ps.size() ; i ++ )
{
Person p
= ps.get(i);
System.out.println(p.toString());
}

可以看到上面的代码使用了TypeToken,它是gson提供的数据类型转换器,可以支持各种数据集合类型转换。

Gson的基本使用就是这么多,至于annotation方面可以参考gson的官方文档,希望能对初学java和gson的同学有所帮助。










Gson(又称Google Gson)是Google公司发布的一个开放源代码的Java库,主要用途为串行化Java对象为JSON字符串,或反串行化JSON字符串成Java对象。

目录

   [隐藏] 
  • 1 历史
  • 2 各版本发布时间
  • 3 使用方法
  • 4 参考文献
  • 5 外部链接

历史[编辑]

Gson当初是为因应Google公司内部需求而由Google自行研发而来,但自从在2008年五月公开发布第一版后已被许多公司或使用者应用。

各版本发布时间[编辑]

  • May 13, 2013: Version 2.2.4
  • May 11, 2012: Version 2.2.1
  • May 5, 2012: Version 2.2
  • December 31, 2011: Version 2.1
  • November 13, 2011: Version 2.0
  • April 13, 2011: Version 1.7.1 Release
  • April 12, 2011: Version 1.7 Release
  • Nov 24, 2010: Version 1.6 Release
  • Aug 19, 2010: Version 1.5 Release
  • October 9, 2009: Version 1.4 Beta release
  • April 1, 2009: Version 1.3 Release (April Fools)
  • January 12, 2009: Version 1.3 Beta release
  • August 29, 2008: Version 1.2 release (better late than never :))
  • July 18, 2008: Version 1.1.1 release
  • July 1, 2008: Version 1.1 release (Happy Canada's Day!!!)
  • June 17, 2008: Version 1.0.1 release
  • May 22, 2008: Version 1.0 release

使用方法[编辑]

Gson的应用主要为toJson与fromJson两个转换函数,而在使用这种对象转换之前需先创建好对象的类以及其成员才能成功的将JSON字符串成功转换成相对应的对象。

  class Examples {
    private int answer1 = 100;
    private String answer2 = "Hello world!";
    Examples(){
    }     // default constructor
  }

串行化JAVA对象成JSON字符串

   Examples example1 = new Examples();
   Gson gson = new Gson();
   String json = gson.toJson(example1);

==> json is {"answer1":100,"answer2":"Hello world!"}

反串行化JSON字符串成对应的JAVA对象

Examples example2= gson.fromJson(json,Examples.class);

==> example2即與example1相同

对象example1通过toJson串行化成JSON字符串传递,再声明一个对象example2为接收了JSON后通过fromJson反串行化成example2,故example1与example2相同

参考文献[编辑]

  • Gson User Guide 这是Gson使用者导览的协作平台,里面有更多使用示例与技术细节可供参考









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

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

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


下面的例子中我们示例如何将一个数据转换成 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() = Alice
student.getName() = Bob
student.getName() = Carol
student.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 = #FFFFFF
map.get = #0000FF
map.get = #FFFF00
map.get = #008000
map.get = #000000
map.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()        = Duke
student.getAddress()     = Menlo Park
student.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"}

你可能感兴趣的:(Gson简要使用笔记)