Spring使用FastJson作为消息转换器时,不能使用Swagger的问题

因为Fast作为JSON的序列化与反序列化一些优点,在项目中使用了FastJson库的FastJsonHttpMessageConverter4 作为Spring的消息转换器,可替换后,发现http://localhost:8081/swagger-ui.html页面能打开,但API内容都不见了。但v2/api-docs倒是能打开。
替换回Spring默认的Jackson2,页面打开正常。经过抓包,发现使用不同的转换器时,页面打开请求的URL是不同的。使用FastJson时,到swagger-resources/configuration/ui请求后,就结束了。而默认的Jackson2在此之后,又多了几个请求。对比swagger-resources/configuration/ui请求的响应数据,发现Jacson2比FastJson多了几个JSON数据项。
再返回系统中,查看日志。Debug跟踪发现MessageConverter的writeInternal方法内,写入的是UiConfiguration对象。而该类的一些属性使用了一些Jackson2的注解。正是这些注解的属性在FastJson中没有输出出来。这个类的输出,发现使用Jackson2来进行。
于是新写一个类,继承FastJsonHttpMessageConverter4 ,覆写writeInternal方法。使用该类作为消息转换器。测试正常。
public class SwaggerFastJsonHttpMessageConverter4 extends FastJsonHttpMessageConverter4 {
private ObjectMapper mapper = new ObjectMapper();

@Override
protected void writeInternal(Object obj, //
Type type, //
HttpOutputMessage outputMessage //
) throws IOException, HttpMessageNotWritableException {
if (type == springfox.documentation.swagger.web.UiConfiguration.class) {
HttpHeaders headers = outputMessage.getHeaders();
ByteArrayOutputStream outnew = new ByteArrayOutputStream();
mapper.writeValue(outnew, obj);
outnew.flush();
headers.setContentLength(outnew.size());
OutputStream out = outputMessage.getBody();
outnew.writeTo(out);
outnew.close();
} else {
super.writeInternal(obj, type, outputMessage);
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
Spring Boot 是一个基于 Spring 的轻量级框架,可以快速搭建基于 Spring 的应用程序。而 Fastjson 是一个高性能的 Java 序列化和反序列化库,可以处理复杂的 JSON 数据。 如果想要在 Spring Boot 中自定义 Fastjson 作为 JSON 消息转换器,可以按照以下步骤进行操作: 首先,在 pom.xml 文件中引入 Fastjson 的依赖,可以通过以下代码来添加依赖: ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.78</version> </dependency> ``` 然后,在 Spring Boot 的配置类中配置 Fastjson 作为 JSON 消息转换器。可以通过以下代码来实现: ```java @Configuration public class FastjsonConfig { @Bean public HttpMessageConverters fastjsonHttpMessageConverter() { FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); converter.setDefaultCharset(Charset.forName("UTF-8")); List<MediaType> supportedMediaTypes = new ArrayList<>(); supportedMediaTypes.add(MediaType.APPLICATION_JSON); converter.setSupportedMediaTypes(supportedMediaTypes); FastJsonConfig config = new FastJsonConfig(); config.setSerializerFeatures(SerializerFeature.PrettyFormat); converter.setFastJsonConfig(config); return new HttpMessageConverters(converter); } } ``` 最后,在 Spring Boot 的主类中加上 @EnableWebMvc 注解,启用自定义的 JSON 消息转换器。 通过以上步骤,就成功地使用Spring Boot 自定义 Fastjson 作为 JSON 消息转换器。这样可以方便地处理 JSON 数据,提升了系统的性能和效率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值