如何使用 Java 中的 @Expose 註解從 JSON 中排除一個欄位?


Gson @Expose 註解可用於標記一個欄位是否公開或不公開(包含或不包含)以序列化或反序列化。@Expose 註解可以接受兩個引數,每個引數都是一個布林值,可以取值 truefalse。為讓 GSON 對 @Expose 註解做出響應,我們必須使用 GsonBuilder 類建立一個 Gson 例項,並需要呼叫 excludeFieldsWithoutExposeAnnotation() 方法進行配置從對沒有 Expose 註解的序列化或反序列化進行考慮的所有欄位中排除 Gson。

語法

public GsonBuilder excludeFieldsWithoutExposeAnnotation()

示例

import com.google.gson.*;
import com.google.gson.annotations.*;
public class JsonExcludeAnnotationTest {
   public static void main(String args[]) {
      Employee emp = new Employee("Raja", 28, 40000.00);
      Gson gson = new GsonBuilder().setPrettyPrinting().create();
      String jsonStr = gson.toJson(emp);
      System.out.println(jsonStr);
      gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create();
      jsonStr = gson.toJson(emp);
      System.out.println(jsonStr);
   }
}
// Employee class
class Employee {
   @Expose(serialize = true, deserialize = true)
   public String name;
   @Expose(serialize = true, deserialize = true)
   public int age;
   @Expose(serialize = false, deserialize = false)
   public double salary;
   public Employee(String name, int age, double salary) {
      this.name = name;
      this.age = age;
      this.salary = salary;
   }
}

輸出

{
 "name": "Raja",
 "age": 28,
 "salary": 40000.0
}
{
 "name": "Raja",
 "age": 28
}

更新於: 2020 年 7 月 6 日

3K+ 瀏覽量

啟動您的職業生涯

完成教程以獲得認證

開始學習
廣告
© . All rights reserved.