該問(wèn)題解決已合并入fastjson 1.2.15版本,請(qǐng)使用1.2.15+版本就不需要做下面的改造了
FastJson是阿里巴巴開(kāi)源的高性能JSON轉(zhuǎn)換工具立由。我們?cè)谑褂肧pring MVC需要進(jìn)行JSON轉(zhuǎn)換時(shí)秧骑,通常會(huì)使用FastJson提供的FastJsonHttpMessageConverter零截。但是在我們使用了Swagger2的工程中使用它之后帖世,我們的Api文檔就無(wú)法工作了(雖然swagger-ui界面可以展現(xiàn)么夫,但是沒(méi)有任何api內(nèi)容盐茎,并且通過(guò)訪問(wèn)/v2/api-docse兴垦,我們得到的返回時(shí){},而不是之前的文檔配置內(nèi)容了字柠。
通過(guò)下載FastJson源碼之后探越,單步調(diào)試可以確定問(wèn)題在于FastJson默認(rèn)提供的Serializer轉(zhuǎn)換springfox.documentation.spring.web.json.Json的結(jié)果為{}。
解決方法:
1窑业、fastjson版本為1.2.10以上钦幔,fastjson 1.2.15以下時(shí),F(xiàn)astJsonHttpMessageConverter沒(méi)有暴露fastjson對(duì)Serializer配置常柄。更新到新版本之后鲤氢,可以方便我們加入對(duì)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中加入自定義序列化類(lèi)
實(shí)現(xiàn)FastJsonHttpMessageConverter的子類(lèi)西潘,并在構(gòu)造函數(shù)中卷玉,加入springfox.documentation.spring.web.json.Json類(lèi)與SwaggerJsonSerializer的映射關(guān)系,使得在轉(zhuǎn)換的時(shí)候喷市,碰到springfox.documentation.spring.web.json.Json就使用我們自己實(shí)現(xiàn)的SwaggerJsonSerializer來(lái)進(jìn)行轉(zhuǎn)換相种,具體如下:
public class FastJsonHttpMessageConverterEx extends FastJsonHttpMessageConverter {
public FastJsonHttpMessageConverterEx() {
super();
this.getFastJsonConfig().getSerializeConfig().put(Json.class, SwaggerJsonSerializer.instance);
}
}
最后,在配置文件中用FastJsonHttpMessageConverterEx替換原來(lái)的FastJsonHttpMessageConverter即可品姓。
2寝并、直接升級(jí)fastjson版本。
![微信公眾號(hào)歡迎關(guān)注.jpg](https://upload-images.jianshu.io/upload_images/6376767-003987c3f2bf2e60.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)