Google Gson 序列化 null 值

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

示例:

(1) POJO 类


  1. public class User {
  2. private String account;
  3. private String password;
  4. private String name;
  5. private int age;
  6. public String getAccount() {
  7. return account;
  8. }
  9. public void setAccount(String account) {
  10. this.account = account;
  11. }
  12. public String getPassword() {
  13. return password;
  14. }
  15. public void setPassword(String password) {
  16. this.password = password;
  17. }
  18. public String getName() {
  19. return name;
  20. }
  21. public void setName(String name) {
  22. this.name = name;
  23. }
  24. public int getAge() {
  25. return age;
  26. }
  27. public void setAge(int age) {
  28. this.age = age;
  29. }
  30. @Override
  31. public String toString() {
  32. return "User [account=" + account + ", password=" + password + ", name=" + name + ", age=" + age + "]";
  33. }
  34. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48

(2) 单元测试


  1. @Test
  2. public void test() throws IOException {
  3. Gson gson = new Gson();
  4. User user = new User();
  5. user.setAccount("test");
  6. user.setName("Test");
  7. user.setAge(20);
  8. System.out.println(gson.toJson(user));
  9. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

运行结果:

Google Gson 序列化 null 值

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


  1. @Test
  2. public void test() throws IOException {
  3. Gson gson = new GsonBuilder()
  4. .serializeNulls()
  5. .create();
  6. User user = new User();
  7. user.setAccount("test");
  8. user.setName("Test");
  9. user.setAge(20);
  10. System.out.println(gson.toJson(user));
  11. }

运行结果:

Google Gson 序列化 null 值

Google Gson 序列化 null 值

相关推荐