Google Gson 字段过滤:基于 Gson 版本

x33g5p2x  于2021-12-25 转载在 Go  
字(2.0k)|赞(0)|评价(0)|浏览(492)

本文内容大多基于官方文档和网上前辈经验总结,经过个人实践加以整理积累,仅供参考。

当为生成的 Google Gson 对象指定版本信息时,可以使用 @Since 和 @Until 注释实现字段过滤。@Since 和 @Until 都接收一个 double 类型参数。

@Since 当设置的 Gson 对象版本大于或等于其所接收的参数时导出该字段

@Until 当设置的 Gson 对象版本小于其所接收的参数时导出该字段

示例

(1) POJO 对象

public class User {

    private String account;

    @Since(2)
    private String password;

    private String name;

    @Until(4)
    private int age;

    public User() {}

    public User(String account, String password, String name, int age) {
        this.account = account;
        this.password = password;
        this.name = name;
        this.age = age;
    }

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User [account=" + account + ", password=" + password + ", name=" + name + ", age=" + age + "]";
    }

}

(2) 测试代码

@Test
public void test() throws IOException {
    User user = new User("admin", "123456", "John", 30);
    String userStr = "{\"account\":\"normal\",\"password\":\"xyz123\",\"name\":\"Normal\",\"age\":25}";

    Gson gson = new GsonBuilder()
        .setVersion(1)
        .create();
    System.out.println(gson.toJson(user));
    System.out.println(gson.fromJson(userStr, User.class));

    gson = new GsonBuilder()
        .setVersion(2)
        .create();
    System.out.println(gson.toJson(user));
    System.out.println(gson.fromJson(userStr, User.class));

    gson = new GsonBuilder()
        .setVersion(3)
        .create();
    System.out.println(gson.toJson(user));
    System.out.println(gson.fromJson(userStr, User.class));

    gson = new GsonBuilder()
        .setVersion(4)
        .create();
    System.out.println(gson.toJson(user));
    System.out.println(gson.fromJson(userStr, User.class));

    gson = new GsonBuilder()
        .setVersion(5)
        .create();
    System.out.println(gson.toJson(user));
    System.out.println(gson.fromJson(userStr, User.class));
}

运行结果:

相关文章