设为首页 加入收藏

TOP

SpringBoot更改HttpMessageConverters使用FastJson出现乱码问题
2019-09-17 18:43:15 】 浏览:22
Tags:SpringBoot 更改 HttpMessageConverters 使用 FastJson 出现 乱码 问题

1、出现问题的现象!如下截图,使用SpringBoot 进行开发,接口返回的内容出现中文乱码?

接口内容想要返回的内容:

 

页面返回内容:

惊喜不?意外不?

为什么出现这个情况?不例外的话,很多同事都是替换了SpringBoot自带的Json框架为FastJson解析工具了。

在替换的过程中,没有注意编码格式造成的!

 

 

@SpringBootApplication(scanBasePackages = {"com.spring.resource.cloud*"}) @ServletComponentScan({"com.spring.resource.cloud*"}) public class ResourceUploadGuestApplication { public static void main(String[] args) { SpringApplication.run(ResourceUploadGuestApplication.class, args); } @Bean public HttpMessageConverters fastJsonHttpMessageConverters(){ //创建FastJson信息转换对象
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter(); //创建Fastjosn对象并设定序列化规则
        FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        //规则赋予转换对象
 fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig); return new HttpMessageConverters(fastJsonHttpMessageConverter); } }

 

 

 

2、解决问题呗!

我们从上面的代码可以看出,在进行数据转换的时候,直接食用FastJson进行替换了原本的默认转换工具。那既然出现问题,一定是新的转换工具出现了问题!

那我们在设定转换过程,是不是可以设定具体转换之后的数据类型及编码格式呢?答案是肯定的!

 @Bean public HttpMessageConverters fastJsonHttpMessageConverters(){ //创建FastJson信息转换对象
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter(); //创建Fastjosn对象并设定序列化规则
        FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); // 中文乱码解决方案
        List<MediaType> mediaTypes = new ArrayList<>(); mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);//设定json格式且编码为UTF-8 fastJsonHttpMessageConverter.setSupportedMediaTypes(mediaTypes); //规则赋予转换对象
 fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig); return new HttpMessageConverters(fastJsonHttpMessageConverter); }

 

这样就解决了乱码问题了!

3、为什么这么修改呢?

如果你看到结果之后,想知道为啥这么修改的话,debug!

初始化的时候,我们看到

SupportedMediaTypes值为 */* 这样对于很多浏览器是识别不了具体的格式和编码类型的,所以出现乱码和非格式化的样子!

 

 

 

(2)指定格式个编码类型之后,出现了JSON格式和UTF-8编码格式,其实对应枚举对象就是

 

/**
* Public constant media type for {@code application/json;charset=UTF-8}.
*/
public final static MediaType APPLICATION_JSON_UTF8;

 

 

 

  小白看问题,浅显不深究

如若表达不清晰或存疑,可留言指教!

      感谢来过

  放松一下啦,找找下图几个方脸吧!

————————————————————————————————————————————————

      (^?_?^)  (^?_?^)(^?_?^)(^?_?^)(^?_?^)(^?_?^)

       (^?_?^)[^?_?^](^?_?^)(^?_?^)[^?_?^](^?_?^)

        (^?_?^)(^?_?^)(^?_?^)(^?_?^)(^?_?^)

          (^?_?^)[^?_?^](^?_?^)(^?_?^)

            (^?_?^)(^?_?^)(^?_?^)

              (^?_?^)[^?_?^]

                  (^?_?^)

————————————————————————————————————————————————

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇面向服务的体系架构 SOA(三) --.. 下一篇linux mysql数据库安装

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目