Springboot2.x整合fastjson
SpringBoot2.0如何集成fastjson?在網上查了一堆資料,但是各文章的說法不一,有些還是錯的,可能只是簡單測試一下就認爲ok了,最後有沒生效都不知道。恰逢公司項目需要將JackSon換成fastjson,因此自己來實踐一下SpringBoot2.0和fastjson的整合,同時記錄下來方便自己後續查閱。
一、Maven依賴說明
SpringBoot的版本爲: 2.1.4.RELEASE
在pom文件中添加fastjson的依賴:
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>
二、整合
我們寫一個配置類WebConfig實現WebMvcConfigurer接口,然後重寫configureMessageConverters方法。具體的代碼如下:
import cn.jiangdoc.web.interceptor.AuthorizationInterceptor;
import cn.jiangdoc.web.interceptor.LoginInterceptor;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
/**
* 使用fastjson代替jackson
* @param converters
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
/*
先把JackSon的消息轉換器刪除.
備註: (1)源碼分析可知,返回json的過程爲:
Controller調用結束後返回一個數據對象,for循環遍歷conventers,找到支持application/json的HttpMessageConverter,然後將返回的數據序列化成json。
具體參考org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor的writeWithMessageConverters方法
(2)由於是list結構,我們添加的fastjson在最後。因此必須要將jackson的轉換器刪除,不然會先匹配上jackson,導致沒使用fastjson
*/
for (int i = converters.size() - 1; i >= 0; i--) {
if (converters.get(i) instanceof MappingJackson2HttpMessageConverter) {
converters.remove(i);
}
}
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
//自定義fastjson配置
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(
SerializerFeature.WriteMapNullValue, // 是否輸出值爲null的字段,默認爲false,我們將它打開
SerializerFeature.WriteNullListAsEmpty, // 將Collection類型字段的字段空值輸出爲[]
SerializerFeature.WriteNullStringAsEmpty, // 將字符串類型字段的空值輸出爲空字符串
SerializerFeature.WriteNullNumberAsZero, // 將數值類型字段的空值輸出爲0
SerializerFeature.WriteDateUseDateFormat,
SerializerFeature.DisableCircularReferenceDetect // 禁用循環引用
);
fastJsonHttpMessageConverter.setFastJsonConfig(config);
// 添加支持的MediaTypes;不添加時默認爲*/*,也就是默認支持全部
// 但是MappingJackson2HttpMessageConverter裏面支持的MediaTypes爲application/json
// 參考它的做法, fastjson也只添加application/json的MediaType
List<MediaType> fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
converters.add(fastJsonHttpMessageConverter);
}
}
三、測試
(1)代碼
要測試fastjson是否整合成功的話,我們只需要在實體類中使用一下fastjson的註解就ok。如果註解生效了,說明fastjson整合成功了。直接看代碼
import com.alibaba.fastjson.annotation.JSONField;
import com.psx.gqxy.common.base.ModelResult;
import lombok.Data;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.List;
@RestController
public class TestController {
@GetMapping("/json")
public ModelResult<JsonBean> testJson() {
ModelResult<JsonBean> result = new ModelResult<>();
JsonBean jsonBean = new JsonBean();
jsonBean.setBirthDay(new Date());
jsonBean.setName("測試");
result.setData(jsonBean);
return result;
}
@Data
class JsonBean {
private String name;
@JSONField(format = "yyyy年MM月dd日")
private Date birthDay;
private List<String> qqList;
}
}
(2)效果
通過這個2步的測試,發現fastjson的註解生效了,也就說明整合成功了
四、雜談
SpringBoot2.0後,有些東西改變了。在SpringBoot 1.X時代,整合fastjson是可以不排除JackSon消息轉換器的。但在SpringBoot2.X時代,必須要排除JackSon消息轉換器。