SpringBoot String类型为null 转换为空字符串

@Configuration
@EnableWebMvc
public class JsonObjectMapper implements WebMvcConfigurer {

/**
 * 专门处理http json null 转 "" 字符串的问题
 *
 * @param converters
 */
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
    initGlobalJackson2ObjectMapperBuilder(builder);
    ObjectMapper objectMapper = builder.createXmlMapper(false).build();
    objectMapper.setSerializerFactory(objectMapper.getSerializerFactory().withSerializerModifier(new MyNullBeanSerializerModifier()));
    MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
    jackson2HttpMessageConverter.setObjectMapper(objectMapper);
    converters.add(jackson2HttpMessageConverter);
}

static public void initGlobalJackson2ObjectMapperBuilder(Jackson2ObjectMapperBuilder builder) {
    //全局共有的序列化反序列化用builder参数设置即可
}


@Bean("jackson2ObjectMapperBuilderCustomizer")
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
    Jackson2ObjectMapperBuilderCustomizer customizer = new Jackson2ObjectMapperBuilderCustomizer() {
        @Override
        public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
            initGlobalJackson2ObjectMapperBuilder(jacksonObjectMapperBuilder);
        }
    };
    return customizer;
}


static public class MyNullStringJsonSerializer extends JsonSerializer {

    @Override
    public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
            throws IOException, JsonProcessingException {
        if (o == null) {
            jsonGenerator.writeString("--");
        }
    }
}


static public class MyNullBeanSerializerModifier extends BeanSerializerModifier {
    // 字符串等类型
    private JsonSerializer _nullJsonSerializer = new MyNullStringJsonSerializer();

    @Override
    public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List beanProperties) {
        //循环所有的beanPropertyWriter
        for (int i = 0; i < beanProperties.size(); i++) {
            BeanPropertyWriter writer = (BeanPropertyWriter) beanProperties.get(i);
            //判断字段的类型,如果是array,list,set则注册nullSerializer
            if (writer.getPropertyType().equals(String.class)) {
                writer.assignNullSerializer(this._nullJsonSerializer);
            }
        }
        return beanProperties;
    }

}

}