在进行序列化如何过滤为null的属性,empty的属性,或者default的属性。

一、全局注册 objectMapper.setSerializationInclusion(Include.ALWAYS);

二、具体类上打注解

@JsonSerialize(include = Inclusion.NON_NULL)
public class MyTypeWithoutNulls
    public String mayHaveValue; // will not be included if value is null

三、具体属性上打注解

@JsonInclude(Include.NON_NULL)
public Date getBirthday() {
  return birthday;
public class User {
private int id;
    private String name;
    private Date birthday;
    public int getId() {
        return id;
    public void setId(int id) {
        this.id = id;
    public String getName() {
        return name;
    public void setName(String name) {
        this.name = name;
    //将该标记放在属性上,如果该属性为NULL则不参与序列化
    //如果放在类上边,那对这个类的全部属性起作用
    //Include.Include.ALWAYS 默认
    //Include.NON_DEFAULT 属性为默认值不序列化
    //Include.NON_EMPTY 属性为 空(“”)  或者为 NULL 都不序列化
    //Include.NON_NULL 属性为NULL 不序列化
    @JsonInclude(Include.NON_NULL)
    public Date getBirthday() {
        return birthday;
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
//测试方法
ObjectMapper mapper = new ObjectMapper();
User user = new User(1,"jack",null);
String outJson = mapper.writeValueAsString(user);
System.out.println(outJson);
//测试结果
//{"id":1,"name":"jack"}
ObjectMapper mapper = new ObjectMapper();
//通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化
//Include.Include.ALWAYS 默认
//Include.NON_DEFAULT 属性为默认值不序列化
//Include.NON_EMPTY 属性为 空(“”)  或者为 NULL 都不序列化
//Include.NON_NULL 属性为NULL 不序列化
mapper.setSerializationInclusion(Include.NON_NULL);
User user = new User(1,"",null);
String outJson = mapper.writeValueAsString(user);
System.out.println(outJson);