美文网首页SpringBoot
SpringBoot中使用FastJson中文乱码解决

SpringBoot中使用FastJson中文乱码解决

作者: 小强不可爱 | 来源:发表于2018-02-18 22:50 被阅读0次

SpringBoot中使用FastJson有两种方式。
1,启动类继承WebMvcConfigurerAdapter

@SpringBootApplication  
public class MybootApplication extends WebMvcConfigurerAdapter  {
    // 配置fastJson  替换jackson
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        //定义一个convert 转换消息的对象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        // 2 添加fastjson 的配置信息 比如 是否要格式化 返回的json数据
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.PrettyFormat
        );
        fastConverter.setFastJsonConfig(fastJsonConfig);
        // 解决乱码的问题
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(fastMediaTypes);
        converters.add(fastConverter);
    }
   public static void main( String[] args )   {
        SpringApplication.run(MybootApplication.class, args);
   }
} 

2,使用@Bean注入FastJsonHttpMessageConverter

@SpringBootApplication
public class MybootApplication {
    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters(){
        //1、先定义一个convert转换消息的对象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        //2、添加fastJson的配置信息,比如:是否要格式化返回json数据;
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        //3、在convert中添加配置信息
        //处理中文乱码问题
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(fastMediaTypes);

        fastConverter.setFastJsonConfig(fastJsonConfig);
        HttpMessageConverter<?> converter = fastConverter;
        return new HttpMessageConverters(converter);
    }
    public static void main(String[] args) {
        SpringApplication.run(MybootApplication.class, args);
    }
}

处理中文乱码第三种方式:在接口中添加produces属性

@RequestMapping(value = "/demo",produces = "application/json; charset=utf-8")
public Demo getDemo(){
        Demo demo = new Demo();
        demo.setId("01");
        demo.setName("张三");
        demo.setDate(new Date());
        return demo;
    }
//这样中文乱码问题就OK了
{
    "date":"2018-02-18 22:25",
    "id":"01",
    "name":"张三"
}

相关文章

网友评论

    本文标题:SpringBoot中使用FastJson中文乱码解决

    本文链接:https://www.haomeiwen.com/subject/pazyzxtx.html