如果字段的值为空,那么如何将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;
}
当前回答
您可以使用以下映射器配置:
mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);
从2.5开始,您可以使用:
mapper.setSerializationInclusion(Include.NON_NULL);
其他回答
如果使用Spring,则为全局配置
@Configuration
public class JsonConfigurations {
@Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.serializationInclusion(JsonInclude.Include.NON_NULL);
builder.serializationInclusion(JsonInclude.Include.NON_EMPTY);
builder.failOnUnknownProperties(false);
return builder;
}
}
这将适用于Spring boot 2.0.3+和Jackson 2.0+
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ApiDTO
{
// your class variable and
// methods
}
对于Jackson 2.5使用:
@JsonInclude(content=Include.NON_NULL)
对于Jackson>1.9.11和<2.x,请使用@JsonSerialize注释来实现:
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
您可以使用以下映射器配置:
mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);
从2.5开始,您可以使用:
mapper.setSerializationInclusion(Include.NON_NULL);