Computer >> Máy Tính >  >> Lập trình >> Java

Cách sử dụng @Until chú thích bằng thư viện Gson trong Java?


@ Chú thích cho đến khi có thể sử dụng với setVersion () phương thức của GsonBuilder lớp. Chú thích này có thể áp dụng cho một trường trong lớp java và chấp nhận float làm đối số. Đối số này đại diện cho số phiên bản trong đó lĩnh vực đã được tuần tự hóa. Chú thích @Until có thể quản lý việc lập phiên bản của các lớp JSON trong dịch vụ web .

Cú pháp

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

Ví dụ

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;
   @Until(1.1)
   private String empTech;
   @Until(1.1)
   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;
   }
}

Đầu ra

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
{
   "empName": "Adithya",
   "empId": 115
}