解決Spring使用FastJsonHttpMessageConverter時Swagger2失效的辦法

該問題解決已合并入fastjson 1.2.15版本,請使用1.2.15+版本就不需要做下面的改造了

FastJson是阿里巴巴開源的高性能JSON轉(zhuǎn)換工具。我們在使用Spring MVC需要進行JSON轉(zhuǎn)換時,通常會使用FastJson提供的FastJsonHttpMessageConverter。但是在我們使用了Swagger2的工程中使用它之后,我們的Api文檔就無法工作了(雖然swagger-ui界面可以展現(xiàn),但是沒有任何api內(nèi)容,并且通過訪問/v2/api-docse,我們得到的返回時{},而不是之前的文檔配置內(nèi)容了。

通過下載FastJson源碼之后,單步調(diào)試可以確定問題在于FastJson默認提供的Serializer轉(zhuǎn)換springfox.documentation.spring.web.json.Json的結(jié)果為{}。

解決方法:

1、fastjson版本為1.2.10以上,fastjson 1.2.15以下時,F(xiàn)astJsonHttpMessageConverter沒有暴露fastjson對Serializer配置。更新到新版本之后,可以方便我們加入對springfox.documentation.spring.web.json.Json的序列化支持。


public class SwaggerJsonSerializer implements ObjectSerializer, ObjectDeserializer {

public final static SwaggerJsonSerializer instance = new SwaggerJsonSerializer();

@Override

public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {

SerializeWriter out = serializer.getWriter();

Json json = (Json) object;

out.write(json.value());

}

@Override

public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {

return null;

}

@Override

public int getFastMatchToken() {

return 0;

}

}


FastJsonHttpMessageConverter中加入自定義序列化類

實現(xiàn)FastJsonHttpMessageConverter的子類,并在構(gòu)造函數(shù)中,加入springfox.documentation.spring.web.json.Json類與SwaggerJsonSerializer的映射關(guān)系,使得在轉(zhuǎn)換的時候,碰到springfox.documentation.spring.web.json.Json就使用我們自己實現(xiàn)的SwaggerJsonSerializer來進行轉(zhuǎn)換,具體如下:


public class FastJsonHttpMessageConverterEx extends FastJsonHttpMessageConverter {

public FastJsonHttpMessageConverterEx() {

super();

this.getFastJsonConfig().getSerializeConfig().put(Json.class, SwaggerJsonSerializer.instance);

}

}


最后,在配置文件中用FastJsonHttpMessageConverterEx替換原來的FastJsonHttpMessageConverter即可。

2、直接升級fastjson版本。


![微信公眾號歡迎關(guān)注.jpg](https://upload-images.jianshu.io/upload_images/6376767-003987c3f2bf2e60.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容