在我的请求模型中,我有一个像生日
的字段
@NotNull
@Schema(example = "19680228", type = "String", format = "yyyyMMdd", pattern = "([0-9]{4})(?:[0-9]{2})([0-9]{2})", required = true, nullable = false)
@JsonDeserialize(using = CustomDateDeserializer.class)
private OffsetDateTime birthDate;
是 offsetDateTime
键入类型,但是,请求启动仅包含格式yyyymmdd的日期部分。这是要求,不能更改。没关系,我已经用我的定制的序列化器
来解决这个问题,而且一切都很好。
基于OpenAPI文档和某些帖子( https://github.com/oai/openapi-specification/blob/main/main/versions/3.0.3.md#data-types ,在Openapi /Swagger-File中声明日期的正确方法是什么?< /a >),我知道OpenAPI支持ISO8601 日期
和日期时间
,在这种情况下,不需要 staters
日期
或日期时间
。
但是,如果您由于遗留代码或没有更改的能力而需要其他一些格式,则该文档指出 type
应为 String
,格式应指定日期为哪种格式,模式
应作为REGEX提供。
这正是我在上述 @schema
注释中所做的。
但是,当我去 https://editor.swagger.io/ yaml 文件中,我的请求模型和控制器生成的API仍然包含 出生日期>
和示例
的格式不正确,甚至没有考虑到:
这是它在我的模型中显示的方式:
如您所见,格式
仍在获得 OffSetDateTime
的格式,并且根本没有示例。
我的控制器也一样:
如何使生日以 yyyymmdd
?例如,如何使其显示为 1972026
在Swagger Editor中显示?
我在Spring Boot应用程序中使用OpenAPI/Swagger 3。
In my request model, I have a field like
@NotNull
@Schema(example = "19680228", type = "String", format = "yyyyMMdd", pattern = "([0-9]{4})(?:[0-9]{2})([0-9]{2})", required = true, nullable = false)
@JsonDeserialize(using = CustomDateDeserializer.class)
private OffsetDateTime birthDate;
My birthday
is of OffsetDateTime
type, however, request comming in contains only date portion in format yyyyMMdd. This is requirement and cannot be changed. And this is OK, I already take care of that with my CustomDateDeserializer
and it is all working fine.
Based on OpenAPI documentation and some post (https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#data-types, What is the correct way to declare a date in an OpenAPI / Swagger-file?), I know that OpenAPI supports ISO8601 date
and date-time
, in which case, no pattern
is needed and type should be provided as date
or date-time
.
However, in case you require some other format due to legacy code or no ability to change, the documentation states that type
should be String
, format
should specify which format the date is in, and pattern
should be provided as regex.
And this is exactly what I am doing in the above @Schema
annotation.
However, when I go to https://editor.swagger.io/ and paste my .yaml file into it, the API generated for both my request model and my controller still contain incorrect formatting for birthdate
and the example
is not even taken into consideration:
Here is how it shows in my model:

As you can see, the format
is still getting the format for OffsetDateTime
and there is no example at all.
Same for my controller:

How do I make birthday show up as yyyyMMdd
? For example, how to make it show as 19720226
in swagger editor?
I am using OpenApi/Swagger 3 in a Spring Boot application.
发布评论