【视频&交流平台】
http://study.163.com/course/introduction.htm?courseId=1004329008&utm_campaign=commission&utm_source=400000000155061&utm_medium=share
http://study.163.com/course/introduction.htm?courseId=1004638001&utm_campaign=commission&utm_source=400000000155061&utm_medium=share
https://gitee.com/happyangellxq520/spring-boot
http://412887952-qq-com.iteye.com/blog/2321532
关注spring boot微信公众号,第一时间了解最新的Spring Boot动态,当前已经更新到:《Spring Boot葵花宝典:初现江湖》 、《Spring Boot葵花宝典:初出茅庐》
需求缘起:
在整理《Spring Boot完美使用FastJson解析JSON数据》章节代码的时候,发现在使用FastJson的时候,中文乱码了,很奇怪,比很久还很久之前怎么没有出现中文乱码嘛?可能见鬼了吧,好了,不管是不是鬼,既然碰到了,就得处理。对于这个乱码还是很好处理的。
一、Spring Boot接入FastJson的方式回顾
在之前的代码,我们已经介绍过了,如何在Spring Boot中接入FastJson,这里不详细介绍,如果没有记忆的,可以翻看之前的文章,这里只简单的说明下。
接入FastJson有两种常用的方式:
其一:继承 WebMvcConfigurerAdapter覆写configureMessageConverters,定义FastJsonHttpMessageConverter对象,然后进行基本的设置,最后添加到List<HttpMessageConverter<?>>中。
其二:定义返回值为HttpMessageConverters的bean,在方法中同样定义FastJsonHttpMessageConverter对象,进行基本的设置,最后使用new HttpMessageConverters(FastJsonHttpMessageConverter) 做为方法的返回值。
二、Spring Boot 中文乱码的产生
上面的两种方式,都需要使用到FastJsonHttpMessageConverter进行配置,这里中文乱码的原因,我们没有配置响应的MediaType为UTF-8编码,只需要设置下即可。
三、Spring Boot 中文乱码的解决
既然知道是少了配置,那么重要的是FastJson支持配置MediaType嘛,很高兴的告诉你,是支持的,这里提供方式二的源码如下:
@Bean public HttpMessageConverters fastJsonHttpMessageConverters() { // 1、需要先定义一个 convert 转换消息的对象; FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); //2、添加fastJson 的配置信息,比如:是否要格式化返回的json数据; FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); //2-1 处理中文乱码问题 List<MediaType> fastMediaTypes = new ArrayList<>(); fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8); fastConverter.setSupportedMediaTypes(fastMediaTypes); //3、在convert中添加配置信息. fastConverter.setFastJsonConfig(fastJsonConfig); HttpMessageConverter<?> converter = fastConverter; return new HttpMessageConverters(converter); }
这里解决乱码核心的部分是:
//2-1 处理中文乱码问题 List<MediaType> fastMediaTypes = new ArrayList<>(); fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8); fastConverter.setSupportedMediaTypes(fastMediaTypes);
———— 微信公众号 ————
提供Spring Boot资讯、技术文章,具体关注方式,搜索springboot或者扫描以下二维码即可关注: