跳至主要內容

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

程序猿DD原创Spring BootSwaggerSpring Boot大约 2 分钟

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

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

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

下面具体说说,如何来解决这个问题。

更新fastjson版本

更新fastjson版本为1.2.10以上,在之前的版本中FastJsonHttpMessageConverter没有暴露fastjson对Serializer配置。更新到新版本之后,可以方便我们加入对springfox.documentation.spring.web.json.Json的序列化支持。

本文采用1.2.12为例:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.12</version>
</dependency>

实现自定义序列化类

通过实现ObjectSerializerObjectDeserializer 接口,分别定义目标的序列化实现和反序列化实现。这里,我们只需要重写write方法,实现序列化过程,将springfox.documentation.spring.web.json.Json对象中的json文档正确返回即可。

public class Json {
    private final String value;

    public Json(String value) {
        this.value = value;
    }

    @JsonValue
    @JsonRawValue
    public String value() {
        return this.value;
    }
}

通过查看springfox.documentation.spring.web.json.Json源码,并单步调试即可知道swagger-ui所需要的返回内容就是Json对象中的value字段提供的。因此我们只需要在write方法中,将Json对象的value值输出即可,具体如下:

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> 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即可。

【转载请注明出处】:https://blog.didispace.com/fastjson-swagger-solution/

上次编辑于:
贡献者: 程序猿DD