当前位置: 移动技术网 > IT编程>软件设计>面向对象 > SpringBoot更改HttpMessageConverters使用FastJson出现乱码问题

SpringBoot更改HttpMessageConverters使用FastJson出现乱码问题

2018年03月23日  | 移动技术网IT编程  | 我要评论

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;

 

 

 

  小白看问题,浅显不深究

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

      感谢来过

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

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

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

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

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

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

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

              (^ _ ^)[^ _ ^]

                  (^ _ ^)

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

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网