解决Spring使用FastJsonHttpMessageConverter时Swagger2失效的办法

该问题解决已合并入fastjson 1.2.15版本,请使用1.2.15+版本就不需要做下面的改造了

FastJson是阿里巴巴开源的高性能JSON转换工具。我们在使用Spring MVC需要进行JSON转换时,通常会使用FastJson提供的FastJsonHttpMessageConverter。但是在我们使用了Swagger2的工程中使用它之后,我们的Api文档就无法工作了(虽然swagger-ui界面可以展现,但是没有任何api内容,并且通过访问/v2/api-docse,我们得到的返回时{},而不是之前的文档配置内容了。

通过下载FastJson源码之后,单步调试可以确定问题在于FastJson默认提供的Serializer转换springfox.documentation.spring.web.json.Json的结果为{}。

解决方法:

1、fastjson版本为1.2.10以上,fastjson 1.2.15以下时,FastJsonHttpMessageConverter没有暴露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中加入自定义序列化类

实现FastJsonHttpMessageConverter的子类,并在构造函数中,加入springfox.documentation.spring.web.json.Json类与SwaggerJsonSerializer的映射关系,使得在转换的时候,碰到springfox.documentation.spring.web.json.Json就使用我们自己实现的SwaggerJsonSerializer来进行转换,具体如下:


public class FastJsonHttpMessageConverterEx extends FastJsonHttpMessageConverter {

public FastJsonHttpMessageConverterEx() {

super();

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

}

}


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

2、直接升级fastjson版本。


![微信公众号欢迎关注.jpg](https://upload-images.jianshu.io/upload_images/6376767-003987c3f2bf2e60.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

你可能感兴趣的:(解决Spring使用FastJsonHttpMessageConverter时Swagger2失效的办法)