OpenAPI 在 Spring 引导应用程序中转义 JSON 响应

OpenAPI escapes JSON response in Spring Boot application

我最近尝试为我的 Sprint Boot 应用程序生成 OpenAPI 文档。我将以下行添加到我的 pom.xml

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>1.2.30</version>
</dependency>

但是当我在本地主机上大摇大摆-ui URL 时,我得到了这个页面

我检查了 /v3/api-docs 处的 JSON,我得到的响应开始于:

"{\"openapi\":\"3.0.1\",\"info\":{\"title\":\"OpenAPI definition\",\"version\":\"v0\"},\"servers\":[{\"url\":\"https://localhost:8900/tds\",

我可以看到正在指定 openapi 字段,但看起来整个响应都被字符串化了,而不仅仅是 JSON。由于似乎没有 OpenAPI 的任何配置,我假设它是从我的 Spring 启动配置中获取的,但我不知道在哪里。

我遇到了同样的问题。在我的例子中,我在扩展 WebMvcConfigurer 的 class 中覆盖了 configureMessageConverters(List<HttpMessageConverter<?>> converters)。 Springdoc 使用在那里配置的转换器。

首先我将一些自定义转换器添加到转换器中,然后是 StringHttpMessageConverter。对于 clazz = String.classmediaType = application/json,两个转换器的 canWrite(Class<?> clazz, MediaType mediaType) 方法返回 true。因此使用了第一个,它将 JSON 转义为字符串。

当我更改它以便首先添加 StringHttpMessageConverter 时,将使用那个代替,并在不转义的情况下序列化 JSON 对象。

这已在 Spring Boot 2.5.3 中修复:

https://github.com/spring-projects/spring-boot/releases/tag/v2.5.3

https://github.com/spring-projects/spring-boot/issues/27361

这是一个小的解决方法,只需指向 yaml 版本: springdoc.swagger-ui.url=/v3/api-docs.yaml

gson 配置为默认 JSON 解析器