Google Gson 禁止序列化内部类

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

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

1 新建包含内部类的 POJO 类

public class User {

    private String account;

    private String password;

    private String name;

    private int age;

    private Address address;

    public User() {}

    public User(String account, String password, String name, int age, double longtitude, double latitude) {
        this.account = account;
        this.password = password;
        this.name = name;
        this.age = age;
        this.address = new Address();
        this.address.setLongtitude(longtitude);
        this.address.setLatitude(latitude);
    }

    public class Address {

        private double longtitude;

        private double latitude;

        public double getLongtitude() {
            return longtitude;
        }

        public void setLongtitude(double longtitude) {
            this.longtitude = longtitude;
        }

        public double getLatitude() {
            return latitude;
        }

        public void setLatitude(double latitude) {
            this.latitude = latitude;
        }

        @Override
        public String toString() {
            return "Address [longtitude=" + longtitude + ", latitude=" + latitude + "]";
        }

    }

    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;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

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

}

2 测试代码

@Test
public void test() throws IOException {
    User user = new User("ACCOUNT", "PASSWORD", "NAME", 25, 99.9999, 111.1111);
    Gson gson = new Gson();
    System.out.println(gson.toJson(user));
    gson = new GsonBuilder()
        .disableInnerClassSerialization()
        .create();
    System.out.println(gson.toJson(user));
}

运行结果:

相关文章