首先我们在网上所看到的代码,大多数长这样
package com.km66.repairshop.config;import cn.hutool.core.date.DateUtil;import com.fasterxml.jackson.core.JsonGenerator;import com.fasterxml.jackson.core.JsonParser;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.JsonSerializer;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.SerializerProvider;import com.fasterxml.jackson.databind.module.SimpleModule;import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Primary;import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;import java.io.IOException;import java.sql.Timestamp;/**
* @author Sir丶雨轩
* @date 2019/3/4 15:03
*/@Configurationpublic class JacksonConfig {
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
SerializerProvider serializerProvider = objectMapper.getSerializerProvider();
serializerProvider.setNullValueSerializer(new JsonSerializer<Object>() {
@Override
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
jsonGenerator.writeString("");
}
});
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Timestamp.class, new JsonSerializer<Timestamp>() {
@Override
public void serialize(Timestamp value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeString(DateUtil.format(value,"yyyy-MM-dd HH:mm:ss"));
}
});
objectMapper.registerModule(simpleModule);
objectMapper.configure(JsonParser.Feature.ALLOW\_UNQUOTED\_CONTROL_CHARS, true) ;
objectMapper.configure(JsonParser.Feature.ALLOW\_SINGLE\_QUOTES, true) ;
objectMapper.configure(JsonGenerator.Feature.ESCAPE\_NON\_ASCII, true);
return objectMapper;
}}
其实这样没错,但是在我这里死活不好使,最终解决方案,加上如下代码
PS:在Spring Web的配置中 一般此类会实现WebMvcConfigurer接口
@Autowired
private ObjectMapper objectMapper;
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.removeIf(item -> item instanceof FastJsonHttpMessageConverter || item instanceof MappingJackson2HttpMessageConverter);
converters.add(new MappingJackson2HttpMessageConverter(objectMapper));
}
评论区