I have a spring webservice that returns a json response. I\'m using the example given here to create the service: http://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-exam
Since version 1.6 we have new annotation JsonSerialize (in version 1.9.9 for example).
Example:
@JsonSerialize(include=Inclusion.NON_NULL)
public class Test{
...
}
Default value is ALWAYS.
In old versions you can use JsonWriteNullProperties, which is deprecated in new versions. Example:
@JsonWriteNullProperties(false)
public class Test{
...
}
For all you non-xml config folks:
ObjectMapper objMapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
HttpMessageConverter msgConverter = new MappingJackson2HttpMessageConverter(objMapper);
restTemplate.setMessageConverters(Collections.singletonList(msgConverter));
Since Jackson is being used, you have to configure that as a Jackson property. In the case of Spring Boot REST services, you have to configure it in application.properties
or application.yml
:
spring.jackson.default-property-inclusion = NON_NULL
source
Setting the spring.jackson.default-property-inclusion=non_null
option is the simplest solution and it works well.
However, be careful if you implement WebMvcConfigurer somewhere in your code, then the property solution will not work and you will have to setup NON_NULL serialization in the code as the following:
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
// some of your config here...
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter(objectMapper);
converters.add(jsonConverter);
}
}
If you are using Jackson 2, the message-converters tag is:
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="prefixJson" value="true"/>
<property name="supportedMediaTypes" value="application/json"/>
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
<property name="serializationInclusion" value="NON_NULL"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
As of Jackson 2.0, @JsonSerialize(include = xxx)
has been deprecated in favour of @JsonInclude