兩種方法:
一、在啓動類中覆寫的configureMessageConverters方法裏添加設置
/**
* 重寫configureMessageConverters方法
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
/*
* 1、需要先定義一個 convert 轉換消息的對象;
* 2、添加fastJson 的配置信息,比如:是否要格式化返回的json數據;
* 3、在convert中添加配置信息.
* 4、將convert添加到converters當中.
*
*/
// 1、需要先定義一個 convert 轉換消息的對象;
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
//2、添加fastJson 的配置信息,比如:是否要格式化返回的json數據;
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(
SerializerFeature.PrettyFormat
);
//解決中文亂碼問題:在方法內部添加這段代碼
List<MediaType> fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
fastConverter.setSupportedMediaTypes(fastMediaTypes);
//3、在convert中添加配置信息.
fastConverter.setFastJsonConfig(fastJsonConfig);
//4、將convert添加到converters當中.
converters.add(fastConverter);
}
二、在controller上的@ReqRequestMapping註解上添加produces = "application/json; charset=utf-8"
@RequestMapping(value="/getDemo",produces = "application/json; charset=utf-8")
public Demo getDemo(){
Demo demo = new Demo();
demo.setId(1);
demo.setName("張三");
demo.setCreateTime(new Date());
return demo;
}