如何解决HttpMessageNotWritableException:没有使用OpenApi Spring生成器的带有预设Content-Type'null'的转换器
我正在(渐进式)春季启动项目中使用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;
}
}
我生成的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
我的确切错误消息已经存在一个问题: Springboot HttpMessageNotWritableException: No converter for [...] with preset Content-Type 'null']但是我仍然认为上下文不同,因为我生成了POJO,所以我无法控制它们,并且因为插件应该适当地生成所有内容,所以我一开始就不会遇到这个问题。
解决方法
对我来说问题出在行内:
responses:
"200":
description: default response
content:
'*/*' # <---- here
schema:
它应该是'*/*'
而不是'application/json'
默认情况下,spring generator区分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) |
,
您需要在 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(这可以满足您的需求),但欢迎您将生产设置为多种内容类型的字符串数组。例如,要允许 XML 输出,您可以在生产属性中添加“text/html”:
@RequestMapping(path = "your_path",products = {"application/json","text/xml"})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。