Pedro Silva Pedro Silva - 2 months ago 8x
Java Question

How to ignore "null" or empty properties in Spring when generating Json

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 (

), 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)


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


If not, then you can configure the ObjectMapper in the MappingJackson2HttpMessageConverter like so:

class WebMvcConfiguration extends WebMvcConfigurationSupport {
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        for(HttpMessageConverter converter: converters) {
            if(converter instanceof MappingJackson2HttpMessageConverter) {
                ObjectMapper mapper = ((MappingJackson2HttpMessageConverter)converter).getObjectMapper()