How to ignore "null" or empty properties in json, globally, using Spring configuration
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);
}
}
}
}
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>
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