如何忽略“null”使用Spring配置全局或json中的空属性 [英] How to ignore "null" or empty properties in json, globally, using Spring configuration
问题描述
我正在尝试仅返回具有值的属性,但也会返回null。
I'm trying to return only the properties that have values, but the null ones are also being returned.
我知道有一个注释可以执行此操作( @JsonInclude(Include.NON_NULL)
),但是我需要在每个实体类中使用这些。
I know that there's an annotation that does this ( @JsonInclude(Include.NON_NULL)
), but then I need these in every single entity class.
所以,我的问题是:有没有办法通过spring配置全局配置? (最好避免使用XML)
So, my question is: Is there a way to configure this globally through spring config? (avoiding XML, preferably)
编辑:似乎这个问题被认为是重复的,但我不这么认为。这里真正的问题是如何通过spring配置来配置它,这是我在其他问题中找不到的。
It seems that this question has been considered a duplicate, but I don't think so. The real question here is how to configure it through spring config, which I couldn't find in other questions.
推荐答案
如果你正在使用Spring Boot,这很简单:
If you are using Spring Boot, this is as easy as:
spring.jackson.serialization-inclusion=non_null
如果没有,那么你可以在MappingJackson2HttpMessageConverter中配置ObjectMapper,如下所示:
If not, then you can configure the ObjectMapper in the MappingJackson2HttpMessageConverter like so:
@Configuration
class WebMvcConfiguration extends WebMvcConfigurationSupport {
@Override
protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
for(HttpMessageConverter converter: converters) {
if(converter instanceof MappingJackson2HttpMessageConverter) {
ObjectMapper mapper = ((MappingJackson2HttpMessageConverter)converter).getObjectMapper()
mapper.setSerializationInclusion(Include.NON_NULL);
}
}
}
}
这篇关于如何忽略“null”使用Spring配置全局或json中的空属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!