Google Gson简明教程

简介

Gson是Google出品的一个JSON解析library,它可以将任意的Java对象转换为JSON string,也可以将JSON string转换为对应的Java对象。
官方介绍如下:

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.

Gson can work with arbitrary Java objects including pre-existing objects that you do not have source code of.

maven依赖

<dependencies>
    <!--  Gson: Java to Json conversion -->
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.7</version>
    </dependency>
</dependencies>

Gson

序列化&反序列化

通过Gson的toJson和fromJson方法来完成Serialization&Deserialization。

友情提示

This is the main class for using Gson. Gson is typically used by first constructing a Gson instance and then invoking toJson(Object) or fromJson(String, Class) methods on it. Gson instances are Thread-safe so you can reuse them freely across multiple threads.

Gson是线程安全的(Thread-Safe),可以在多线程间共享使用。

基本类型
// Serialization
Gson gson = new Gson();
gson.toJson(1);            // ==> 1
gson.toJson("abcd");       // ==> "abcd"
gson.toJson(new Long(10)); // ==> 10
int[] values = { 1 };
gson.toJson(values);       // ==> [1]

// Deserialization
int one = gson.fromJson("1", int.class);
Integer one = gson.fromJson("1", Integer.class);
Long one = gson.fromJson("1", Long.class);
Boolean false = gson.fromJson("false", Boolean.class);
String str = gson.fromJson("\"abc\"", String.class);
String[] anotherStr = gson.fromJson("[\"abc\"]", String[].class);
简单对象

1、序列化

class User {
  private long id;
  private String name;
  private int age;
  private transient int gender;
  User() {
    // no-args constructor
  }
  //省略setter/getter方法
}

// Serialization
User user = new User();
user.setId(3);
user.setName("ricky");
user.setAge(27);

Gson gson = new Gson();
String json = gson.toJson(user);  
System.out.println(json);

输出结果:

{"id":3,"name":"ricky","age":27}

需要注意几点:

  • 序列化对象推荐使用基本类型属性
  • 默认情况下,属性值为null在序列化时会被忽略
  • 默认情况下,transient修饰的属性在序列化和反序列化时会被忽略不输出。
2、反序列化
// Deserialization
Gson gson = new Gson();
User obj2 = gson.fromJson(json, User.class);

复杂对象

class User {
    private long id;
    private String name;
    private int age;
    private transient int gender;
    private Address address;
    //省略getter/setter方法

}
// Serialization
User user = new User();
user.setId(3);
user.setName("ricky");
user.setAge(27);
Address address = new Address();
address.setProvince("湖北省");
address.setCity("武汉市");
address.setDistrict("武昌区");
user.setAddress(address);
Gson gson = new Gson();
String json = gson.toJson(user);  
System.out.println(json);

输出结果:
{“id”:3,”name”:”ricky”,”age”:27,”address”:{“province”:”湖北省”,”city”:”武汉市”,”district”:”武昌区”}}

数组

Gson gson = new Gson();
int[] ints = {1, 2, 3, 4, 5};
String[] strings = {"abc", "def", "ghi"};

// Serialization
gson.toJson(ints);     // ==> [1,2,3,4,5]
gson.toJson(strings);  // ==> ["abc", "def", "ghi"]

// Deserialization
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class); 
// ==> ints2 will be same as ints

Gson支持多维数组Serialization/Deserialization。

集合

基本类型
Gson gson = new Gson();
Collection<Integer> ints = Lists.immutableList(1,2,3,4,5);

// Serialization
String json = gson.toJson(ints);  // ==> json is [1,2,3,4,5]

// Deserialization
Type collectionType = new TypeToken<Collection<Integer>>(){}.getType();
Collection<Integer> ints2 = gson.fromJson(json, collectionType);
// ==> ints2 is same as ints
对象集合
List<User> list = new ArrayList<User>();
        User user = new User();
        user.setId(1);
        user.setName("ricky");
        user.setAge(27);
        list.add(user);

        Gson gson = new Gson();
        // Serialization
        String json = gson.toJson(list);  

        System.out.println(json);

        // Deserialization
        Type listType = new TypeToken<List<User>>(){}.getType();
        List<User> userList = gson.fromJson(json, listType);
        System.out.println(userList);

泛型类

class Foo<T> {
  T value;
}
Gson gson = new Gson();
Foo<Bar> foo = new Foo<Bar>();

Type fooType = new TypeToken<Foo<Bar>>() {}.getType();
gson.toJson(foo, fooType);

gson.fromJson(json, fooType);

指定属性序列化名称

默认情况下,Gson使用属性名作为序列化名称,我们也可以使用SerializedName注解来为属性指定一个不同于属性名的名称。

class Person {
    @SerializedName("first_name")
    private String firstName;
    @SerializedName("middle_name")
    private String middleName;
    @SerializedName("last_name")
    private String lastName;
    private int age;
    //省略getter/setter方法
}

Person p = new Person();
p.setFirstName("Shark");
p.setMiddleName("Q");
p.setLastName("ONeal");
p.setAge(27);

Gson gson = new GsonBuilder().serializeNulls().create();
String json = gson.toJson(p);   //{"first_name":"Shark","middle_name":"Q","last_name":"ONeal","age":27}

控制Gson Serialization and Deserialization行为

JSON 输出格式
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(someObject);
序列化null属性
Gson gson = new GsonBuilder().serializeNulls().create();

自定义Serialization and Deserialization

有些时候Gson默认的Serialization and Deserialization满足不了我们的需求,例如DateTime,此时我们就需要自定义了。
Gson 允许我们注册自定义的serializers and deserializers. 这部分定义如下:

  • Json Serializers: Need to define custom serialization for an object
  • Json Deserializers: Needed to define custom deserialization for a
    type
  • Instance Creators: Not needed if no-args constructor is available or
    a deserializer is registered


Excluding Fields From Serialization and Deserialization

1、修饰符

import java.lang.reflect.Modifier;
Gson gson = new GsonBuilder()
    .excludeFieldsWithModifiers(Modifier.STATIC)
    .create();

2、@Expose注解

Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()

JsonParser

有些情况下,如果需要手工解析JSON string,可以使用com.google.gson.JsonParser类,如下:

String json = "{\"first_name\":\"Shark\",\"middle_name\":\"Q\",\"last_name\":\"ONeal\",\"age\":27}";

        JsonParser parser = new JsonParser();
        JsonObject jObj = parser.parse(json).getAsJsonObject();
        String first_name = jObj.get("first_name").getAsString();   //Shark
        System.out.println(first_name);

参考资料

https://github.com/google/gson/blob/master/UserGuide.md

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值