您的位置:首页 > 理论基础 > 计算机网络

Springboot使用FastJsonHttpMessageConverter导致Swagger2失效

2017-03-06 00:00 1471 查看

依赖版本

springboot:1.4.3.RELEASE

fastjson:1.2.7。

问题

加入进行api管理,访问 http://localhost:8080/v2/api-docs ,返回结果为{}。

查看相关代码。



Swagger2Controller相关代码



Json相关代码



AbstractMessageConverterMethodProcessor相关代码



FastJsonHttpMessageConverter相关代码

一路debug下来,发现原因在FastJsonHttpMessageConverter.writeInternal方法序列化obj时候返回为{},而obj对象的class为Json。Json只声明了jackson序列化的方式,而fastjson不兼容。

中间出现的其他问题

另一位同事使用的demo没有出现这个问题,而只有我这边出现了问题,排查发现。



我的代码debug下来如上图,Converter有9个,使用的是FastJsonHttpMessageConverter



同事的代码debug如上图,Converter有10个,使用的是MappingJackson2HttpMessageConverter

springboot比较坑的地方,可能由于某个配置不同,导致我两使用的json序列化包依赖不同,但是实在找不到这个配置不同在哪,特此记录一下。

##解决方案

重写Swagger2Controller

使用jackson序列

升级fastjson到1.2.15+版本。

3方法是发现问题后,突然在大神的博客中发现早已经解决该bug....

大神博客解决方案:http://blog.didispace.com/fastjson-swagger-solution/

另附笔者当前更新的fastjson1.2.24中代码

protected void writeInternal(Object obj, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
HttpHeaders headers = outputMessage.getHeaders();
ByteArrayOutputStream outnew = new ByteArrayOutputStream();
int len = JSON.writeJSONString(outnew, this.fastJsonConfig.getCharset(), obj, this.fastJsonConfig.getSerializeConfig(), this.fastJsonConfig.getSerializeFilters(), this.fastJsonConfig.getDateFormat(), JSON.DEFAULT_GENERATE_FEATURE, this.fastJsonConfig.getSerializerFeatures());
headers.setContentLength((long)len);
OutputStream out = outputMessage.getBody();
outnew.writeTo(out);
outnew.close();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐