Google Gson 序列化 null 值
Gson 在默认情况下不会序列化导出 null 值
示例:
(1) POJO 类
- public class User {
- private String account;
- private String password;
- private String name;
- private int age;
- 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;
- }
- @Override
- public String toString() {
- return "User [account=" + account + ", password=" + password + ", name=" + name + ", age=" + age + "]";
- }
- }
- 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) 单元测试
- @Test
- public void test() throws IOException {
- Gson gson = new Gson();
- User user = new User();
- user.setAccount("test");
- user.setName("Test");
- user.setAge(20);
- System.out.println(gson.toJson(user));
- }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
运行结果:
如果需要序列化导出完整的 JSON 字符串(包括 null 值)则需要使用 com.google.gson.GsonBuilder 类
- @Test
- public void test() throws IOException {
- Gson gson = new GsonBuilder()
- .serializeNulls()
- .create();
- User user = new User();
- user.setAccount("test");
- user.setName("Test");
- user.setAge(20);
- 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