7、serializeNulls支持空对象序列化

在对象序列化为json字符串时,默认是不序列化NULL对象的,如果在序列化时设置serializeNulls了,就可以支持NULL的序列化。注意serializeNulls对反序列化没有影响。
示例如下
1、注释掉builder.serializeNulls()

    public static void main(String[] args) {

        GsonBuilder builder = new GsonBuilder();
        /*如果不设置serializeNulls,序列化时默认忽略NULL*/
//      builder.serializeNulls();   // 1
        /*使打印的json字符串更美观,如果不设置,打印出来的字符串不分行*/
        builder.setPrettyPrinting();
        Gson gson = builder.create();
        Person person = new Person();
        person.setId(1);
        person.setName("lzj");
        String json = gson.toJson(person);
        System.out.println(json);

        Person person2 = gson.fromJson(json, Person.class);
        System.out.println(person2);
    }

运行程序,输出:

序列化后的内容为:
{
  "id": 1,
  "name": "lzj",
  "age": 0
}
----------------------------
反序列化后的内容为:
Person [id=1, name=lzj, car=null, age=0]

从输出结果中看一看出,person对象中的car属性是NULL,序列化时没有输出。

2、取消builder.serializeNulls()注释
运行程序,输出
序列化后的内容为:

{
  "id": 1,
  "name": "lzj",
  "car": null,
  "age": 0
}
----------------------------
反序列化后的内容为:
Person [id=1, name=lzj, car=null, age=0]

从输出结果看一看出,NULL值也被序列化了。

猜你喜欢

转载自blog.csdn.net/u010502101/article/details/80555558