如何在Java中使用Gson库序列化空字段?

默认情况下,Gson对象不会将具有 空值的字段序列化为JSON。如果Java对象中的字段为null,则Gson会将其排除。我们可以强制Gson通过GsonBuilder 对空值进行序列化。在创建Gson对象之前,我们需要在GsonBuilder 实例 上调用serializeNulls()方法。一旦serializeNulls()被调用由创建的GSON实例GsonBuilder 可以 包括空字段的序列化JSON。

语法

public GsonBuilder serializeNulls()

示例

import com.google.gson.*;
import com.google.gson.annotations.*;
public class NullFieldTest {
   public static void main(String args[]) {
      GsonBuilder builder = new GsonBuilder();
      builder.serializeNulls();
      Gson gson = builder.setPrettyPrinting().create();
      Employee emp = new Employee(null, 25, 40000.00);
      String jsonEmp = gson.toJson(emp);
      System.out.println(jsonEmp);
   }
}
//员工阶层
class Employee {
   @Since(1.0)
   public String name;
   @Since(1.0)
   public int age;
   @Since(2.0)   public double salary;
   public Employee(String name, int age, double salary) {
      this.name = name;
      this.age = age;
      this.salary = salary;
   }
}

输出结果

{
   "name": null,
   "age": 25,
   "salary": 40000.0
}