如何在 Java 中使用 Gson 的 @Since 注释?
javajsonobject oriented programmingprogramming
@Since 注释 可与 GsonBuilder 类的 setVersion() 方法一起使用。此注释可应用于 Java 类中的字段并接受浮点数作为参数。此参数表示字段已序列化的版本号。这同样适用于反序列化过程。
语法
@Documented @Retention(value=RUNTIME) @Target(value={FIELD,TYPE}) public @interface Since
示例
import com.google.gson.annotations.Since; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class GsonSinceAnnotationTest { public static void main(String[] args) { Employee emp = new Employee(); emp.setEmployeeName("Raja Ramesh"); emp.setEmployeeId(125); emp.setEmployeeTechnology("Java"); emp.setEmploeeAddress("Hyderabad"); System.out.println("Since 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("Since version 1.0"); gsonBuilder = new GsonBuilder(); gson = gsonBuilder.setPrettyPrinting().setVersion(1.0).create(); jsonString = gson.toJson(emp); System.out.println(jsonString); System.out.println("Since 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; @Since(1.0) private String empTech; @Since(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; } }
输出
Since version 0.5 { "empName": "Raja Ramesh", "empId": 125 } Since version 1.0 { "empName": "Raja Ramesh", "empId": 125, "empTech": "Java" } Since version 1.1{ "empName": "Raja Ramesh", "empId": 125, "empTech": "Java", "empAddress": "Hyderabad" }