1. 程式人生 > >Google Gson 禁止序列化內部類

Google Gson 禁止序列化內部類

本文內容大多基於官方文件和網上前輩經驗總結,經過個人實踐加以整理積累,僅供參考。

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

執行結果:
這裡寫圖片描述