在Spring Boot 1.2.3中,我们可以通过属性文件自定义Jackson ObjectMapper。但我没有找到一个属性可以设置Jackson在将Object序列化为JSON字符串时忽略null值。
spring.jackson.deserialization.*= # see Jackson's DeserializationFeature
spring.jackson.generator.*= # see Jackson's JsonGenerator.Feature
spring.jackson.mapper.*= # see Jackson's MapperFeature
spring.jackson.parser.*= # see Jackson's JsonParser.Feature
spring.jackson.serialization.*=
我想存档相同的代码,如
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
答案 0 :(得分:44)
将以下行添加到application.properties
文件中。
spring.jackson.default属性模型 - 包裹体= non_null
对于2.7之前的杰克逊版本:
spring.jackson.serialization系夹杂物= non_null
答案 1 :(得分:12)
在弃用之前,这是一个很好的解决方案:
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
但现在你应该使用:
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ClassName {
...
答案 2 :(得分:10)
对于Spring Boot 1.4.x,您可以将以下行包含在 application.properties
中 spring.jackson.default-property-inclusion=non_null
答案 3 :(得分:6)
这是Spring Boot 1.3.0的增强功能。
很遗憾,您需要在1.2.3
上以编程方式配置它@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class Shop {
//...
}
答案 4 :(得分:5)
类宽,
arn = 'arn:aws:iam::{}:policy/*{}'.format(account_id, p)
versions = iam.list_policy_versions(PolicyArn=arn)['Versions']
属性范围:
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MyModel { .... }
答案 5 :(得分:0)
@Bean
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder mapperBuilder) {
return mapperBuilder.build().setSerializationInclusion(Include.NON_NULL);
}
对我有用的