12

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Pedro Silva
  • 460
  • 2
  • 4
  • 16

4 Answers4

25

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);
            }
        }
    }
}
Jon Peterson
  • 2,966
  • 24
  • 32
6

In newer versions of Spring Boot (2.0+), use:

spring.jackson.default-property-inclusion=non_null
JRA_TLL
  • 1,186
  • 12
  • 23
5

The programmatic alternative to Abolfazl Hashemi's answer is the following:

/**
 * Jackson configuration class.
 */
@Configuration
public class JacksonConfig {

    @Bean
    public ObjectMapper buildObjectMapper() {
       return new ObjectMapper().setSerializationInclusion(Include.NON_NULL);
    }
}

This way, you're basically telling to the Spring container that, every time an ObjectMapper is used, only properties with non-null values are to be included in the mappings.

Another alternative, as per the Spring Boot documentation, for Jackson 2+, is to configure it in the application.properties:

spring.jackson.default-property-inclusion=non_null

EDIT:

If, instead of application.properties one is relying on application.yml, then the following configuration should be used:

spring:
    jackson:
        default-property-inclusion: non_null
António Ribeiro
  • 4,129
  • 5
  • 32
  • 49
4

If you use jackson ObjectMapper for generating json, you can define following custom ObjectMapper for this purpose and use it instead:

<bean id="jacksonObjectMapper" class="com.fasterxml.jackson.databind.ObjectMapper">
   <property name="serializationInclusion">
      <value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
   </property>
</bean>
user85421
  • 28,957
  • 10
  • 64
  • 87
Abolfazl Hashemi
  • 684
  • 7
  • 21