在开发过程中,遇到在属性上加jsoninclude.include.non_null注解,有些属性起了作用,有些却没有起作用,下面使用代码简要说明一下:
@Data
public class demoBean {
private String aNo;
private String aName;
private String aId;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String aCount;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String timeType;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String timeLong;
}
发现timeType与timeLong为空时,过滤成功,aCount为空时,还是传递给了后端。
解决方案一:
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class demoBean {
private String aNo;
private String aName;
private String aId;
private String aCount;
private String timeType;
private String timeLong;
}
在类上加 @JsonInclude(JsonInclude.Include.NON_NULL)注解,发现没有问题。
解决方案二:
@Data
public class demoBean {
private String aNo;
private String aName;
private String aId;
// 该为非驼峰命名法,发现驼峰命名法,传给前端参数改为acount 小写
@JsonInclude(JsonInclude.Include.NON_NULL)
private String abCount;
//private String aCount;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String timeType;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String timeLong;
}
把不起作用属性名改为非驼峰命名法,亦有效。
解决方案三(待测试):
@Data
public class demoBean {
private String aNo;
private String aName;
private String aId;
@JsonProperty
@JsonInclude(JsonInclude.Include.NON_NULL)
private String aCount;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String timeType;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String timeLong;
}
属性前加 @JsonProperty 注解,该方案未测试,如读者有疑问,欢迎反馈。