HttpMessageNotWritableException:没有用于具有预设内容类型 'null'] 和 OpenApi Spring 生成器的 [...] 的转换器

HttpMessageNotWritableException: No converter for [...] with preset Content-Type 'null'] with OpenApi Spring generator

我正在 (gradle) spring 引导项目中使用 openAPI 实现宠物店 API。我使用 openapi 生成器插件生成一个服务器并实现一个简单的请求:

@Service
@RestController
public class PetApiController implements PetApi {

    @Override
    public ResponseEntity<Pet> getPetById(Long petId) {
        Pet p = new Pet();
        p.setId(0L);
        p.setName("fido");
        p.setPhotoUrls(new ArrayList<String>());
        p.setStatus(StatusEnum.AVAILABLE);
        p.setTags(new ArrayList<Tag>());
        Category c = new Category();
        c.setId(3L);
        c.setName("dummy category");
        p.setCategory(c);
        
        ResponseEntity<Pet> r = new ResponseEntity<Pet>(p, HttpStatus.OK);
        
        return r;
    }
}

我生成的 swagger-ui 提供了 xml 和 json 查询请求,但 xml 似乎不起作用:

$ curl -X GET "http://localhost:8080/pet/1" -H  "accept: application/xml"; echo ""

$ curl -X GET "http://localhost:8080/pet/1" -H  "accept: application/json"; echo ""
{"id":0,"name":"fido","category":{"id":3,"name":"dummy category"},"photoUrls":[],"tags":[],"status":"available"}

我什至收到一条错误消息:

2020-09-10 09:04:34.213  WARN 23958 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotWritableException: No converter for [class com.petstore.server.model.Pet] with preset Content-Type 'null']

但是我无法捕获此异常并打印整个上下文,它只发生在 return r

之后

我的确切错误消息已经有一个问题: 但我仍然认为我的上下文不同,因为我生成了我的 POJO,所以我无法控制它们,而且我一开始就不应该有这个问题,因为插件应该适当地生成所有内容。

默认情况下,spring 生成器会歧视 xml,请参阅文档:https://openapi-generator.tech/docs/generators/spring 下的

Option  | Description                                       | Default
--------+---------------------------------------------------+---------
withXml | whether to include support for application/xml    | false
        | content type and include XML annotations in the   |
        | model (works with libraries that provide support  |
        | for JSON and XML)                                 |

对我来说问题在于行:

responses:
        "200":
          description: default response
          content:
            '*/*' # <---- here
              schema:

而不是 '*/*' 应该是 'application/json'

您需要在 pom 文件中使用以下依赖项添加对 xml 格式的支持:

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.1.1</version>
</dependency>

注意:这里的版本是今天最新的。

根据 Peer 的 awnser,我已经解决了我的问题,但这是不同的方式。您需要添加“text/xml”来告诉spring。即使这将您的 API 限制为基于 JSON(这可以满足您的需求),您也可以将 produces 设置为用于多种内容类型的 String 数组。例如,要允许 XML 输出,您可以将“text/html”添加到 produces 属性:

@RequestMapping(path = "your_path", produces = {"application/json", "text/xml"})

就我而言,我的 class Pet 根本没有 getter。

所以我通过为字段添加 get 方法解决了这个问题。