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

发布时间:2024年01月19日

@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;
    }

}

}

文章来源:https://blog.csdn.net/qq_35118528/article/details/135701143
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。