在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;
}
网友评论