首頁 >Java >java教程 >如何在Java中使用Gson函式庫的@Until註解?

如何在Java中使用Gson函式庫的@Until註解?

WBOY
WBOY轉載
2023-09-01 11:41:101061瀏覽

如何在Java中使用Gson函式庫的@Until註解?

@Until 註解可以與 GsonBuilder 類別的 setVersion() 方法一起使用。此註解可以應用於 java 類別中的欄位並接受 float 作為參數。此參數表示欄位已序列化的版本號碼@Until 註解可以管理網路服務中 JSON 類別的版本控制。

語法

@Documented
@Retention(value=RUNTIME)
@Target(value={FIELD,TYPE})
public @interface Until

範例

import com.google.gson.annotations.Until;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class GsonUntilAnnotationTest {
   public static void main(String[] args) {
      Employee emp = new Employee();
      emp.setEmployeeName("Adithya");
      emp.setEmployeeId(115);
      emp.setEmployeeTechnology("Python");
      emp.setEmploeeAddress("Pune");
      System.out.println("Using version 0.5");
      GsonBuilder gsonBuilder = new GsonBuilder();
      Gson gson = gsonBuilder.setPrettyPrinting().setVersion(0.5).create();
      String jsonString = gson.toJson(emp);
      System.out.println(jsonString);
      System.out.println("Using version 1.0");
      gsonBuilder = new GsonBuilder();
      gson = gsonBuilder.setPrettyPrinting().setVersion(1.0).create();
      jsonString = gson.toJson(emp);
      System.out.println(jsonString);
      System.out.println("Using version 1.1");
      gsonBuilder = new GsonBuilder();
      gson = gsonBuilder.setPrettyPrinting().setVersion(1.1).create();
      jsonString = gson.toJson(emp);
      System.out.println(jsonString);
   }
}
// Employee class
class Employee {
   private String empName;
   private int empId;
<strong>   </strong>@Until(1.1)
   private String empTech;
   @Until(1.1<strong>)</strong>
   private String empAddress;
   public String getEmployeeName() {
      return empName;
   }
   public void setEmployeeName(String empName) {
      this.empName = empName;
   }
   public int getEmployeeId() {
      return empId;
   }
   public void setEmployeeId(int empId) {
      this.empId = empId;
   }
   public String getEmployeeTechnology() {
      return empTech;
   }
  public void setEmployeeTechnology(String empTech) {
      this.empTech = empTech;
   }
   public String getEmploeeAddress() {
      return empAddress;
   }
   public void setEmploeeAddress(String empAddress) {
      this.empAddress = empAddress;
   }
}

輸出

Using version 0.5
{
   "empName": "Adithya",
   "empId": 115,
   "empTech": "Python",
   "empAddress": "Pune"
}
Using version 1.0
{
   "empName": "Adithya",
   "empId": 115,
   "empTech": "Python",
   "empAddress": "Pune"
}
Using version 1.1<strong>
</strong>{
   "empName": "Adithya",
   "empId": 115
}

以上是如何在Java中使用Gson函式庫的@Until註解?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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