如果字段的值为空,那么如何将Jackson配置为在序列化期间忽略该字段值。
例如:
public class SomeClass {
// what jackson annotation causes jackson to skip over this value if it is null but will
// serialize it otherwise
private String someValue;
}
如果字段的值为空,那么如何将Jackson配置为在序列化期间忽略该字段值。
例如:
public class SomeClass {
// what jackson annotation causes jackson to skip over this value if it is null but will
// serialize it otherwise
private String someValue;
}
当前回答
您可以设置application.properties:
spring.jackson.default-property-inclusion=non_null
或application.yaml:
spring:
jackson:
default-property-inclusion: non_null
http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
其他回答
在Jackson 2.x中,使用:
@JsonInclude(JsonInclude.Include.NON_NULL)
要使用Jackson>2.0禁止使用空值序列化财产,可以直接配置ObjectMapper,或使用@JsonInclude注释:
mapper.setSerializationInclusion(Include.NON_NULL);
or:
@JsonInclude(Include.NON_NULL)
class Foo
{
String bar;
}
或者,您可以在getter中使用@JsonInclude,这样,如果值不为空,将显示属性。
在我对如何防止Map中的空值和bean中的空字段通过Jackson序列化的回答中,提供了一个更完整的示例。
对于Jackson 2.5使用:
@JsonInclude(content=Include.NON_NULL)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
应该起作用。
Include.NON_EMPTY表示如果属性的值不为null且不为空,则该属性将被序列化。Include.NON_NULL表示如果属性的值不为空,则该属性被序列化。
这已经困扰了我一段时间,我终于找到了问题所在。问题是由于错误的导入。早些时候我一直在使用
com.fasterxml.jackson.databind.annotation.JsonSerialize
已被弃用。只需将导入替换为
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
并将其用作
@JsonSerialize(include=Inclusion.NON_NULL)