我们如何在Java中使用Gson使用@Since注释?
@Since注释可以与使用setVersion()的方法GsonBuilder 类。该注释可以应用于java类中的字段,并接受float作为参数。此参数表示该字段已序列化的版本号。这同样适用于反序列化过程。
语法
@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); } } //员工阶层 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" }