fastjson是阿里出的,儘管近年fasjson爆出過幾回嚴重漏洞,可是平心而論,fastjson的性能的確頗有優點,尤爲是大數據量時的性能優點,因此fastjson依然是咱們的首選;spring boot默認的json解析器是Jackson,替換爲fastjson頗有必要;java
<!-- fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency>
注意:Springboot2.0之後,WebMvcConfigurerAdapter 過期了, 之前1版本繼承WebMvcConfigurerAdapter 來實現的方法不推薦了。下面介紹兩種配置方式,還有一種實現WebMvcConfigurationSupport的方式就不介紹了,道路千萬條,選一條就足夠了:
spring
package com.anson.config; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; @Configuration public class WebConfig { /** * @Author anson * @Description 配置消息轉換器 * @Date: 2019-12-8 11:23:33 * @version: 1.0 * new HttpMessageConverters(true, converters); * 必定要設爲true才能替換不然不會替換 * @return 返回一個消息轉換的bean */ @Bean public HttpMessageConverters fastJsonMessageConverters() { List<HttpMessageConverter<?>> converters = new ArrayList<>(); //須要定義一個convert轉換消息的對象; FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); //添加fastJson的配置信息; FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); //全局時間配置 fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss"); fastJsonConfig.setCharset(Charset.forName("UTF-8")); //處理中文亂碼問題 List<MediaType> fastMediaTypes = new ArrayList<>(); fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8); //在convert中添加配置信息. fastConverter.setSupportedMediaTypes(fastMediaTypes); fastConverter.setFastJsonConfig(fastJsonConfig); converters.add(0, fastConverter); return new HttpMessageConverters(converters); } }
方式2、實現WebMvcConfigurerjson
@Configuration public class WebConfigure implements WebMvcConfigurer
{ /** * 配置消息轉換器 * @param converters */ @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { //須要定義一個convert轉換消息的對象; FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); //添加fastJson的配置信息; FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); //全局時間配置 fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss"); fastJsonConfig.setCharset(Charset.forName("UTF-8")); //處理中文亂碼問題 List<MediaType> fastMediaTypes = new ArrayList<>(); fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8); //在convert中添加配置信息. fastConverter.setSupportedMediaTypes(fastMediaTypes); fastConverter.setFastJsonConfig(fastJsonConfig); converters.add(0,fastConverter); } }