如何在Java中使用Gson库序列化空字段?
默认情况下,Gson对象不会将具有 空值的字段序列化为JSON。如果Java对象中的字段为null,则Gson会将其排除。我们可以强制Gson通过GsonBuilder 类对空值进行序列化。在创建Gson对象之前,我们需要在GsonBuilder 实例 上调用serializeNulls()方法。一旦serializeNulls()被调用由创建的GSON实例GsonBuilder 可以 包括空字段的序列化JSON。
语法
public GsonBuilder serializeNulls()
示例
import com.google.gson.*;
import com.google.gson.annotations.*;
public class NullFieldTest {
public static void main(String args[]) {
GsonBuilder builder = new GsonBuilder();
builder.serializeNulls();
Gson gson = builder.setPrettyPrinting().create();
Employee emp = new Employee(null, 25, 40000.00);
String jsonEmp = gson.toJson(emp);
System.out.println(jsonEmp);
}
}
//员工阶层
class Employee {
@Since(1.0)
public String name;
@Since(1.0)
public int age;
@Since(2.0) public double salary;
public Employee(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
}输出结果
{
"name": null,
"age": 25,
"salary": 40000.0
}热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短