SpringBoot学习之添加fastjson的方式及处理中文乱码

SpringBoot中使用FastJson有两种方式。
处理中文乱码添加代码
List fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
fastConverter.setSupportedMediaTypes(fastMediaTypes);
1,启动类继承WebMvcConfigurationSupport(WebMvcConfigurerAdapter已经过时)

@SpringBootApplication  
public class MybootApplication extends WebMvcConfigurationSupport{
   	// 配置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);
    }
}

3、注解添加produces = “application/json; charset=utf-8”

@RequestMapping(value = "/getDemoEnt",produces = "application/json; charset=utf-8")
public demoEntity getDemoEnt() {
	demoEntity demo = new demoEntity();
	demo.setAge("1");
	demo.setId("00021");
	demo.setName("周杰伦");
	demo.setTime(new Date());
	return demo;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章