1. 默认情况下, Gson生成优化的Json内容, 忽略NULL值。但是GsonBuilder使用GsonBuilder.serializeNulls()方法提供了在Json输出中显示NULL值的标志。
GsonBuilder builder = new GsonBuilder();
builder.serializeNulls();
Gson gson = builder.create();
2. 例子
2.1. 新建一个名为GsonSerializeNulls的Java项目, 同时添加相关jar包。
2.2. 新建Student.java
package com.fj.sn;
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
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 String toString() {
return "Student [name: " + name + ", age: " + age + "]";
}
}
2.3. 新建App.java
package com.fj.sn;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class App {
public static void main(String[] args) {
// 创建一个学生对象
Student student = new Student(null, 21);
Gson gson = new Gson();
String jsonString = gson.toJson(student);
System.out.println(jsonString);
// 1. Gson构造器
GsonBuilder builder = new GsonBuilder();
// 2. 支持序列化空值
builder.serializeNulls();
// 3. 格式良好的输出
builder.setPrettyPrinting();
// 4. 创建Gson对象
gson = builder.create();
// 5. JavaBean转化为JSON字符串
jsonString = gson.toJson(student);
System.out.println(jsonString);
}
}
2.4. 运行项目