spring boot通过jsckson,将返回数据中null值转换成空字符串给前端/app

原文链接: https://www.jianshu.com/p/e8a392496f35

转载:https://www.jianshu.com/p/e8a392496f35

自定义一个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() {
            @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;
}

你可能感兴趣的:(IDEA)