Is there a way when using @ResponseBody annotation to have null values mapped to empty strings?
I have also faced the same problem in my project and I have therefore quickly come up with a solution for the same. This post will surely help all those who have been struggling with the same issue.
Step 1:- Create your Custom Null Handler Serializer.
public class NullSerializer extends StdSerializer
Step 2:- Create a bean of MappingJackson2HttpMessageConverter.
@Bean
@Primary
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
mapper.getSerializerProvider().setNullValueSerializer(new NullSerializer());
jsonConverter.setObjectMapper(mapper);
return jsonConverter;
}
Thank you for taking some time out to read this post. I hope that this was able to resolve your queries to some extent.