Google Gson 序列化 null 值

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

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

Gson 在默认情况下不会序列化导出 null

示例:

(1) POJO 类

public class User {

    private String account;

    private String password;

    private String name;

    private int 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 {
    Gson gson = new Gson();
    User user = new User();
    user.setAccount("test");
    user.setName("Test");
    user.setAge(20);
    System.out.println(gson.toJson(user));
}

运行结果:

如果需要序列化导出完整的 JSON 字符串(包括 null 值)则需要使用 com.google.gson.GsonBuilder

@Test
public void test() throws IOException {
    Gson gson = new GsonBuilder()
        .serializeNulls()
        .create();
    User user = new User();
    user.setAccount("test");
    user.setName("Test");
    user.setAge(20);
    System.out.println(gson.toJson(user));
}

运行结果:

相关文章