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

javajsonobject oriented programmingprogramming更新于 2025/7/13 16:44:17

默认情况下,Gson 对象不会将具有空值的字段序列化为 JSON。如果 Java 对象中的字段为空,Gson 会将其排除。我们可以通过 GsonBuilder 类强制 Gson 序列化空值。我们需要在创建 Gson 对象之前在 GsonBuilder实例上调用 serializeNulls() 方法。一旦调用了 serializeNulls(),由 GsonBuilder创建的 Gson 实例就可以在序列化的 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);
   }
}
// Employee class
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
}

相关文章


有用资源