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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章