SpringBoot 2.0 以上,需要自定义配置项时,则通过实现WebMvcConfigurer接口来实现,WebMvcConfigurerAdapter已经过时了,SpringBoot默认的JSON处理器(解析器)是Jackson,本人用的比较多的是fastjson,fastjson的api用起来更方便一点。当然有时候太过复杂的JSON字符串,使用FastJson有时候会转换失败,只不过一般情况下都不会碰到。本人在写websocket通信时,碰到过字符串使用fastjson解析失败,后来我在websocket模块改用用gson解决的。
修改SpringBoot 2.0默认JSON解析器:
@Configuration
public class AppServerAutoConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowedMethods("*").allowedHeaders("*");
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
// 千万要注意这里
converters.add(0, fastJsonHttpMessageConverter());
}
@SuppressWarnings("rawtypes")
public HttpMessageConverter fastJsonHttpMessageConverter() {
// 1.需要定义一个Convert转换消息的对象
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
// 2.添加fastjson的配置信息,比如是否要格式化返回的json数据
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
// 3.在convert中添加配置信息
fastConverter.setFastJsonConfig(fastJsonConfig);
List<MediaType> fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
fastConverter.setSupportedMediaTypes(fastMediaTypes);
return fastConverter;
}
}