指定了JsonInclude.Include#value的USE_DEFAULTS,以便可以使用更高级别的默认值。如果在属性上使用此选项@JsonInclude,则将使用类的设置(如果存在),否则将使用全局序列化包含规则(通过设置ObjectMapper)。
例子
Java对象
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Employee {
private String name;
private String dept;
private Integer salary;
private boolean fullTime;
@JsonInclude(JsonInclude.Include.NON_NULL)
private List<String> phones;
private Date dateOfBirth;
....
@JsonInclude(JsonInclude.Include.USE_DEFAULTS)
public List<String> getPhones() {
return phones;
}
}
Main类
public class ExampleMain {
public static void main(String[] args) throws IOException {
Employee employee = new Employee();
employee.setName("Trish");
employee.setFullTime(false);
employee.setPhones(new ArrayList<>());
employee.setSalary(Integer.valueOf(2000));
employee.setDateOfBirth(null);
ObjectMapper om = new ObjectMapper();
String jsonString = om.writeValueAsString(employee);
System.out.println(jsonString);
}
}
结果
{"name":"Trish","salary":2000,"fullTime":false}
如在上述输出“phones”没有被序列化,NON_NULL(在字段级别)被忽略,并使用类级别NON_EMPTY选项。如果我们移除phones的getter方法上的@JsonInclude:
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Employee {
private String name;
private String dept;
private Integer salary;
private boolean fullTime;
@JsonInclude(JsonInclude.Include.NON_NULL)
private List<String> phones;
private Date dateOfBirth;
....
public List<String> getPhones() {
return phones;
}
}
结果集
{“ name”:“ Trish”,“ salary”:2000,“ fullTime”:false,“ phones”:[]}
这次包括了“phones”,因为它不是空的。在倒数第二个示例中,'phones’属性上的设置@JsonInclude(JsonInclude.Include.USE_DEFAULTS)可以正常工作。