Gson 2 --GsonBuilder

上一篇地址:http://blog.csdn.net/caesardadi/article/details/11985183


上一篇说到创建Gson实例,使用new Gson(),此时会创建一个带有默认配置 选项的Gson实例,如果不想使用默认配置,那么就可以使用GsonBuilder。


使用GsonBuilder创建Gson 实例:

首先创建GsonBuilder

,然后调用GsonBuilder提供的各种配置方法进行配置,

最后调用GsonBuilder的create方法,将基于当前的配置创建一个Gson实例。


事例如下:

     Gson gson = new GsonBuilder()
     .registerTypeAdapter(Id.class, new IdTypeAdapter())
     .enableComplexMapKeySerialization()
     .serializeNulls()
     .setDateFormat(DateFormat.LONG)
     .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
     .setPrettyPrinting()
     .setVersion(1.0)
     .create();
配置的顺序无关。

默认的配置Date是不包含时区信息的,如果修改,可以调用GsonBuilder的setDateFormat方法。


下面说下配置的属性。

实体类

package com.example.gson;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.util.Date;

/**
 * Student 实体类
 * Created by liu on 13-11-25.
 */
public class Student {
    int age;
    String name;
    @Expose(serialize = true,deserialize = false)
    @SerializedName("bir")
    Date birthday;

    public Student(int age, String name, Date birthday) {
        this.age = age;
        this.name = name;
        this.birthday = birthday;
    }

    public Student(int age, String name) {
        this.age = age;
        this.name = name;
    }


    @Override
    public String toString() {
        if (birthday == null) {
            return "{\"name\":" + name + ", \"age\":" + age + "}";
        } else {
            return "{\"name\":" + name + ", \"age\":" + age + ", \"birthday\":" + birthday.toString() + "}";
        }

    }
}

常用配置方法:


     gsonBuilder.excludeFieldsWithoutExposeAnnotation();

      只导出使用了@Expose注释过的属性,如果没有设置这句,只是在类中相应属性进行设置,是无效的。

       Expose声明使用方法

 public class User {
   @Expose private String firstName;
   @Expose(serialize = false) private String lastName;
   @Expose (serialize = false, deserialize = false) private String emailAddress;
   private String password;
 }
 

其中serialize和deserialize是可选的,默认两个都为true,即toJson和fromJson该属性都会暴露。

如果只有serialize为true,,表示在toJson生成Json数据时会导出该属性,在根据Json数据生成Java对象时不会将值赋给该类型对象的该属性值。


gsonBuilder.setFieldNamingStrategy(FieldNamingPolicy.UPPER_CAMEL_CASE);

字段(即Key值)首字母大写,

注意在属性前面声明了 @SerializedName("bir")的无效,该声明表示在转换时使用指定的名称。


 gsonBuilder.setPrettyPrinting();

 对JSON结果格式化,比如添加换行



gsonBuilder.setVersion

有的字段不是一开始就有的,会随着版本的升级添加进来,那么在进行序列化和返序列化的时候就会根据版本号来选择是否要序列化.  

@Since(版本号)能完美地实现这个功能.还的字段可能,随着版本的升级而删除,那么  

  @Until(版本号)也能实现这个功能,GsonBuilder.setVersion(double)方法需要调用.


这些声明都在com.google.gson.annotations 包中。


gsonBuilder.enableComplexMapKeySerialization() 

支持Map的key为复杂对象的形式  

当Map中数据类型为自定义类型时,需要开启本方法。

如下代码

 Map<Student,String> map = new HashMap<Student, String>();
        map.put(new Student(11,"liupan"),"aaaaaaaaaaaaaaaaaa");
        map.put(new Student(22,"liupan22"),"bbbbbbbbbbbbbbb");

        Gson gson2 = new GsonBuilder().enableComplexMapKeySerialization().create();
        String mapJsonStr =   gson2.toJson(map);
        Log.e("============GsonBuilder Map to jsonStr========================", mapJsonStr);

        Map<Student,String> map2 = gson2.fromJson(mapJsonStr,new TypeToken<Map<Student,String>>(){}.getType());
        Log.e("============GsonBuilder jsonStr to Map========================", map2.toString());



参考 :

https://code.google.com/p/google-gson/

http://blog.csdn.net/lk_blog/article/details/7685169



版权声明:本文为Caesardadi原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。