Google Gson 禁止序列化内部类

1 新建包含内部类的 POJO 类


  1. public class User {
  2. private String account;
  3. private String password;
  4. private String name;
  5. private int age;
  6. private Address address;
  7. public User() {}
  8. public User(String account, String password, String name, int age, double longtitude, double latitude) {
  9. this.account = account;
  10. this.password = password;
  11. this.name = name;
  12. this.age = age;
  13. this.address = new Address();
  14. this.address.setLongtitude(longtitude);
  15. this.address.setLatitude(latitude);
  16. }
  17. public class Address {
  18. private double longtitude;
  19. private double latitude;
  20. public double getLongtitude() {
  21. return longtitude;
  22. }
  23. public void setLongtitude(double longtitude) {
  24. this.longtitude = longtitude;
  25. }
  26. public double getLatitude() {
  27. return latitude;
  28. }
  29. public void setLatitude(double latitude) {
  30. this.latitude = latitude;
  31. }
  32. @Override
  33. public String toString() {
  34. return "Address [longtitude=" + longtitude + ", latitude=" + latitude + "]";
  35. }
  36. }
  37. public String getAccount() {
  38. return account;
  39. }
  40. public void setAccount(String account) {
  41. this.account = account;
  42. }
  43. public String getPassword() {
  44. return password;
  45. }
  46. public void setPassword(String password) {
  47. this.password = password;
  48. }
  49. public String getName() {
  50. return name;
  51. }
  52. public void setName(String name) {
  53. this.name = name;
  54. }
  55. public int getAge() {
  56. return age;
  57. }
  58. public void setAge(int age) {
  59. this.age = age;
  60. }
  61. public Address getAddress() {
  62. return address;
  63. }
  64. public void setAddress(Address address) {
  65. this.address = address;
  66. }
  67. @Override
  68. public String toString() {
  69. return "User [account=" + account + ", password=" + password + ", name=" + name + ", age=" + age + ", address="
  70. + address + "]";
  71. }
  72. }

2 测试代码


  1. @Test
  2. public void test() throws IOException {
  3. User user = new User("ACCOUNT", "PASSWORD", "NAME", 25, 99.9999, 111.1111);
  4. Gson gson = new Gson();
  5. System.out.println(gson.toJson(user));
  6. gson = new GsonBuilder()
  7. .disableInnerClassSerialization()
  8. .create();
  9. System.out.println(gson.toJson(user));
  10. }

运行结果:

Google Gson 禁止序列化内部类

Google Gson 禁止序列化内部类

相关推荐