美文网首页
spring boot 自定义jsckson null转换成空字

spring boot 自定义jsckson null转换成空字

作者: 上官明 | 来源:发表于2016-11-21 16:05 被阅读0次

    在spring boot中,默认配置使用jackson,对象的null值也会被解析成null输出到前台,我们需要把null转换成空字符串

    <b>

    自定义一个ObjectMapper

    package com.kindo.config;
    
    import java.io.IOException;
    
    import com.fasterxml.jackson.core.JsonGenerator;
    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.JsonSerializer;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.SerializerProvider;
    
    public class KindoObjectMapper extends ObjectMapper {
    
        /**
        * 
        */
        private static final long serialVersionUID = 1L;
    
        public KindoObjectMapper() {
            super();
            // 数字也加引号
            // this.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, true);
            // this.configure(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS,
            // true);
            // 空值处理为空串
            this.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
                @Override
                public void serialize(Object value, JsonGenerator jg, SerializerProvider sp)
                        throws IOException, JsonProcessingException {
                    jg.writeString("");
                }
            });
    
        }
    
    }
    

    把自定义的ObjectMapper加入到SpringBoot中,修改SpringBoot启动类

    /**
     * 自定义ObjectMapper
     * 
     * @return
     */
    @Bean
    public MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter() {
        final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        KindoObjectMapper mapper = new KindoObjectMapper();
        converter.setObjectMapper(mapper);
        return converter;
    }
    

    相关文章

      网友评论

          本文标题:spring boot 自定义jsckson null转换成空字

          本文链接:https://www.haomeiwen.com/subject/ppuupttx.html