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));
- }
运行结果:
相关推荐
SXIAOYI 2020-09-16
xiaonuoyal 2020-06-17
SXIAOYI 2020-06-11
yinbaoshiguang 2020-06-09
Chydar 2020-06-02
nalanrumeng 2020-06-01
xiaonuoyal 2020-06-01
nalanrumeng 2020-05-19
ITprivate 2020-04-15
xiaonuoyal 2020-04-14
ITprivate 2020-03-26
ITprivate 2020-02-12
nalanrumeng 2020-01-13
xiaonuoyal 2019-12-07
xiaonuoyal 2019-11-18
TOmyhonour 2019-11-16