HttpMessageNotWritableException:没有带有 OpenApi Spring 生成器的 [...] 预设 Content-Type 'null'] 转换器

pee*_*eer 12 spring spring-boot openapi-generator

我正在(gradle)spring boot 项目中使用 openAPI 实现 petstore 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我生成的 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"}
Run Code Online (Sandbox Code Playgroud)

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

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']
Run Code Online (Sandbox Code Playgroud)

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

我的确切错误消息已经存在一个问题: Springboot HttpMessageNotWritableException: No converter for [...] with preset Content-Type 'null']但我仍然认为我的上下文是不同的,因为我生成了 POJO,所以我无法控制他们,我一开始就不应该遇到这个问题,因为插件应该适当地生成所有内容。

Ale*_*nov 11

对我来说,一个问题是:

responses:
        "200":
          description: default response
          content:
            '*/*' # <---- here
              schema:
Run Code Online (Sandbox Code Playgroud)

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


Ole*_*kov 10

就我而言,我的班级Pet根本没有吸气剂。

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


Cod*_*r17 6

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

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.1.1</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

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


pee*_*eer 3

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)                                 |
Run Code Online (Sandbox Code Playgroud)