我试图创建问题的最小示例。
假设我们有简单的返回对象:
public class Result {
@Schema(example = "2012-01-01")
private LocalDate sampleDate;
// omitted getter and setter
}
由简单的 JAX-RS 端点返回:
@Path("/example")
@Produces(MediaType.APPLICATION_JSON)
public class Resource {
public List<Result> example() {
// omitted implementation
}
}
Open Liberty 中的 MicroProfile OpenAPI 将自动生成以下 OpenAPI (Swagger) 文件:
openapi: 3.0.0
info:
title: Deployed APIs
version: 1.0.0
servers:
- url: http://localhost:9080/api
paths:
/example:
get:
operationId: example
responses:
default:
description: default response
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Result'
components:
schemas:
Result:
type: object
properties:
sampleDate:
type: string
format: date
example: 2012-01-01
问题是嵌入式 Swagger UI 将日期示例显示为空 JS 对象:
我不确定这是否是 Swagger UI 方面的错误,因为如果我不在 Java 注释中提供任何示例 = OpenAPI 文件中的任何示例,它将把示例呈现为当天,例如:
[
{
"sampleDate": "2018-11-27"
}
]
当我手动编辑 OpenAPI 输出时,一切正常。单引号和双引号都解决了这个问题:
...
sampleDate:
type: string
format: date
example: '2012-01-01'
或
...
sampleDate:
type: string
format: date
example: "2012-01-01"
将产生预期的输出:
[
{
"sampleDate": "2012-01-01"
}
]
问题是如何更改注释以获得所需的 OpenAPI 输出。 单引号自动转义:
@Schema(example = "'2012-01-01'")
private LocalDate sampleDate;
将产生:
...
sampleDate:
type: string
format: date
example: '''2012-01-01'''
Java 中的附加双引号对输出没有任何影响:
@Schema(example = "\"2012-01-01\"")
private LocalDate sampleDate;
将产生相同的不带引号的输出:
...
sampleDate:
type: string
format: date
example: 2012-01-01
我知道我可以手动编写 OpenAPI yaml 输出,但这是我最后的选择,因为我不想仅仅因为日期示例的行为不符合我的要求而牺牲自动生成。也许可以实现一些 OASFilter
来自动包装日期的示例值,或者我只是在这里遗漏了一些明显的东西。
最佳答案
我已经确认了您所描述的行为。 这是与 Microprofile OpenAPI 打包在一起的 Swagger-UI 的问题,您可以在此处打开问题: Swagger UI GitHub .
产生的值,不带引号是完全有效的 yaml,所以 UI 应该能够按原样解析它。
关于java - 如何在 MicroProfile OpenAPI 中定义日期示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53501606/