Springboot使用FastJsonHttpMessageConverter导致Swagger2失效
2017-03-06 00:00
1471 查看
依赖版本
springboot:1.4.3.RELEASEfastjson: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(); }
相关文章推荐
- FastJsonHttpMessageConverter设置dateFormat后导致JSONField注解format失效解决办法
- @ResponseBody 返回json字符串的核心类是org.springframework.http.converter.json.MappingJacksonHttpMessageConverter,它使用了Jackson 这个开源的第三方类库。主要是以下两个jar包:jackson-core-asl-1.6.4.jar;jackson-mapper-asl-1.6.4.jar
- SpringMVC中使用FastJsonHttpMessageConverter时Swagger2失效的解决办法
- 使用xml/json格式传输数据 spring mvc(HttpMessageConverter<T>的使用)
- Not found org.springframework.http.converter.json.MappingJacksonHttpMessageConverter
- (4)Spring Boot完美使用FastJson解析JSON数据【从零开始学Spring Boot】
- 解决Spring boot中使用Gson,Swagger2 api-docs无法正常显示json问题
- SPRING MVC3.2案例讲解--使用 Spring 3 MVC HttpMessageConverter 功能构建 RESTful web 服务
- 使用 Spring 3 MVC HttpMessageConverter 功能构建 RESTful web 服务
- Spring Boot使用FastJson解析JSON数据的方法
- Not found org.springframework.http.converter.json.MappingJacksonHttpMessageConverter
- 使用 Spring 3 MVC HttpMessageConverter 功能构建 RESTful web 服务
- 78. Spring Boot完美使用FastJson解析JSON数据【从零开始学Spring Boot】
- 使用 Spring 3 MVC HttpMessageConverter 功能构建 RESTful web 服务
- org.springframework.http.converter.json.MappingJacksonHttpMessageConverter
- 使用 Spring 3 MVC HttpMessageConverter 功能构建 RESTful web 服务
- SSM框架搭建java.lang.ClassNotFoundException: org.springframework.http.converter.json.MappingJacksonHttpMessageConverter
- SPRING MVC3.2案例讲解--使用 Spring 3 MVC HttpMessageConverter 功能构建 RESTful web 服务
- 使用 Spring 3 MVC HttpMessageConverter 功能构建 RESTful web 服务
- 使用 Spring 3 MVC HttpMessageConverter 功能构建 RESTful web 服务