如何在 Java 中使用 Gson 庫序列化空欄位?


預設情況下,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
}

更新時間: 2020 年 7 月 4 日

7 千次瀏覽

開啟您的 職業生涯

完成課程並獲得認證

開始學習
廣告