首頁  >  文章  >  Java  >  如何在Java中使用@Expose註解從JSON中排除一個欄位?

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

PHPz
PHPz轉載
2023-09-16 21:49:02561瀏覽

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

Gson @Expose 註解可用於標記欄位是否公開(包含或不包含)以進行序列化或反序列化。 @Expose 註解 可以採用兩個參數,每個參數都是一個布林值,可以採用值 true false。為了讓GSON 對@Expose 註解做出反應,我們必須使用GsonBuilder 類別建立一個Gson 實例,並且需要呼叫excludeFieldsWithoutExposeAnnotation() 方法,它將Gson 配置為排除所有沒有Expose註釋的字段進行序列化或反序列化。

語法

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)<strong>
</strong>   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
}

以上是如何在Java中使用@Expose註解從JSON中排除一個欄位?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除