使用Gson序列化对象时,默认情况下,对象值为"null"的字段在输出值会被忽略(NOTE:collections和arrays中的null对象会被保留)。如果要使Gson序列化对象输出所有的null值,可使用如下方法进行配置。

1
Gson gson = new GsonBuilder().serializeNulls().create();

NOTE: 当使用Gson序列化null值时,它会添加JsonNull元素到JsonElement结构中。

以下就是使用Gson支持输出null值:

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
public class Foo {
private final String s;
private final int i;

public Foo() {
this(null, 5);
}

public Foo(String s, int i) {
this.s = s;
this.i = i;
}
}

Gson gson = new GsonBuilder().serializeNulls().create();
Foo foo = new Foo();
String json = gson.toJson(foo);
System.out.println(json);

json = gson.toJson(null);
System.out.println(json);

======== OUTPUT ========
{"s":null,"i":5}
null

参考: Gson User Guide


我的博客: http://liumh.com