Search code examples
spring-bootopenapi-generator

OpenAPI escapes JSON response in Spring Boot application


I recently tried to generate OpenAPI documentation for my Sprint Boot application. I added the following lines to my pom.xml

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

But when I hit the swagger-ui URL on my localhost I get this page enter image description here

I checked the JSON at /v3/api-docs and I get a response that starts:

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

I can see that the openapi field is being specified, but it looks like the entire response is stringified instead of just being JSON. Since there doesn't seem to be any configuration for OpenAPI, I assume it's getting that from something in my Spring Boot configuration, but I have no idea where.


Solution

  • I had the same problem. In my case, I have overridden configureMessageConverters(List<HttpMessageConverter<?>> converters) in the class extending WebMvcConfigurer. Springdoc uses the converters that are configured there.

    First I had some custom converter added to the converters first, and then the StringHttpMessageConverter. The canWrite(Class<?> clazz, MediaType mediaType) method of both converters returned true for clazz = String.class and mediaType = application/json. Thus the first one was used, which escaped the JSON as string.

    When I changed it so that the StringHttpMessageConverter is added first, that one is used instead, and serializes the JSON object without escaping.