1. 引入fastjson
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
2. 看看SpringMVC的配置
<!-- 啓用 阿里巴巴 json 開啓對@ResponseBody 和 @RestController的轉Json文件支持-->
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<!-- 如果有多個值,都支持,但是默認使用第一個-->
<value>application/json</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
3. 其實springboot的json亂碼也是這裏沒有設置
@Configuration//指定這是一個Spring boot應用程序
public class App{
@Bean//使用@Bean注入fastJsonHttpMessageConvert
public HttpMessageConverters fastJsonHttpMessageConverters(){
//1.需要定義一個Convert轉換消息的對象
FastJsonHttpMessageConverter fastConverter=new FastJsonHttpMessageConverter();
//2.添加fastjson的配置信息,比如是否要格式化返回的json數據
//
FastJsonConfig fastJsonConfig=new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
//3.在convert中添加配置信息
fastConverter.setFastJsonConfig(fastJsonConfig);
List<MediaType> supportType = new ArrayList<>();
supportType.add(MediaType.valueOf("application/json;charset=UTF-8"));
supportType.add(MediaType.valueOf("text/html;charset=UTF-8"));
fastConverter.setSupportedMediaTypes(supportType);
HttpMessageConverter<?> converter=fastConverter;
return new HttpMessageConverters(converter);
}
}