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

I am trying to return only those properties that have values, but nulls are also returned.

I know there is an annotation that does this ( @JsonInclude(Include.NON_NULL) ), but then I need it in every entity class.

So my question is: is there a way to configure globally through spring configuration? (preferably avoid XML)

EDIT: This question seems to be considered a duplicate, but I don't think so. The real question here is how to configure it with spring config, which I could not find in other questions.

+8
java json spring jackson spring-mvc
source share
3 answers

If you use Spring Boot, it is as simple as:

 spring.jackson.serialization-inclusion=non_null 

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

 @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); } } } } 
+14
source share

If you use jackson ObjectMapper to generate json, for this purpose you can define the following custom ObjectMapper 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> 
+3
source share

The software alternative to Abolfazl Hashemi is as follows:

 /** * Jackson configuration class. */ @Configuration public class JacksonConfig { @Bean public ObjectMapper buildObjectMapper() { return new ObjectMapper().setSerializationInclusion(Include.NON_NULL); } } 

Thus, you basically tell the Spring container that every time you use ObjectMapper , only properties with nonzero values ​​should be included in the mappings.

0
source share

All Articles