How to ignore "null" or empty properties in json, globally, using Spring configuration

Pedro Silva :

I'm trying to return only the properties that have values, but the null ones are also being returned.

I know that there's an annotation that does this ( @JsonInclude(Include.NON_NULL) ), but then I need these in every single entity class.

So, my question is: Is there a way to configure this globally through spring config? (avoiding XML, preferably)

EDIT: 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.

Jon Peterson :

If you are using Spring Boot, this is as easy as:

spring.jackson.serialization-inclusion=non_null

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);
            }
        }
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=454107&siteId=1