Springboot 2.1.1.RELEASE版本修改默认JSON解析器为fastjson

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;
	}

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值