Gson-@Since注解

1 @Since注解的作用

Gson提供@Since注解,用于控制类的Json序列化/反序列化的版本。

2 @Since注解的语法

class Student { 
   @Since(1.0) 
   private int rollNo; 
   
   @Since(1.0) 
   private String name; 
   
   @Since(1.1) 
   private boolean verified;  
}

上面代码中,@Since(1.0)代表第一个版本的属性,@Since(1.1)的verified属性代码是第二个版本新增的属性。

GsonBuilder提供了setVersion() 方法指定需要序列的版本号。

GsonBuilder builder = new GsonBuilder(); 
builder.setVersion(1.0);   
Gson gson = builder.create();

3 @Since注解的示例

3.1 编写核心类

MainApp:

package com.yiidian.gson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Since;

/**
 * 一点教程网 - http://www.yiidian.com
 */
public class MainApp {

    public static void main(String args[]) {

        GsonBuilder builder = new GsonBuilder();
        builder.setVersion(1.0);
        Gson gson = builder.create();
        
        Student student = new Student();
        student.setRollNo(1);
        student.setName("eric");
        student.setVerified(true);

        //指定读取@Since(1.0)版本的属性
        String jsonString = gson.toJson(student);
        System.out.println(jsonString);

        //默认读取所有版本的属性
        gson = new Gson();
        jsonString = gson.toJson(student);
        System.out.println(jsonString);
    }

}

class Student {
    @Since(1.0)
    private int rollNo;

    @Since(1.0)
    private String name;

    @Since(1.1)
    private boolean verified;

    public int getRollNo() {
        return rollNo;
    }

    public void setRollNo(int rollNo) {
        this.rollNo = rollNo;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setVerified(boolean verified) {
        this.verified = verified;
    }

    public boolean isVerified() {
        return verified;
    }
}

3.2 运行测试