Null values as empty strings when using @ResponseBody annotation

前端 未结 2 1133
被撕碎了的回忆
被撕碎了的回忆 2020-12-17 05:49

Is there a way when using @ResponseBody annotation to have null values mapped to empty strings?

2条回答
  •  星月不相逢
    2020-12-17 06:09

    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 {
    
        public NullSerializer(Class t) {
           super(t);
        }
    
        public NullSerializer() {
          this(null);
        }
    
        @Override
        public void serialize(Object o, com.fasterxml.jackson.core.JsonGenerator jsonGenerator, com.fasterxml.jackson.databind.SerializerProvider serializerProvider) throws IOException {
           jsonGenerator.writeString("");
        }
       }
    
    
    

    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.

    提交回复
    热议问题