java - 为 Java LocalDateTime 生成正确的招摇规范
问题描述
我正在尝试在 Spring Boot 应用程序中使用 Swagger Annotations 从 Java 代码中获取 swagger 规范(yaml)。我对模型进行注释,然后运行 springboot 应用程序,然后从http://localhost:8080/v2/api-docs获取规范。
我的模型如下所示:
package com.indiana.core;
import java.time.LocalDateTime;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
@lombok.ToString
@lombok.Getter
@lombok.Setter
public class SampleClass{
@JsonProperty(value = "birth_date_time")
private LocalDateTime birthDateTime;
....
}'
我想为此创建正确的招摇 yaml 斑点。当我访问自动提供 yaml 的 swagger UI 时,我期望如下。
请注意 dateOfBirth 是 Java 8 LocalDateTime 类。但根据 swagger 规范(https://swagger.io/specification/查找数据类型部分),yaml 中的日期应该是类型:“字符串”,格式:日期时间。
'SampleClass:
properties:
dateOfBirth:
type: string
format: date-time'
我现在得到的:
看起来 swagger 正在构建一个详细的定义 LocalDateTime,这不是我正在寻找的。
'"definitions": {
"LocalDateTime": {
"type": "object",
"properties": {
"chronology": {
"$ref": "#/definitions/Chronology"
},
"dayOfMonth": {
"type": "integer",
"format": "int32"
},
"dayOfWeek": {
"type": "string",
"enum": ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"]
},
"dayOfYear": {
"type": "integer",
"format": "int32"
},
"hour": {
"type": "integer",
"format": "int32"
},
"minute": {
"type": "integer",
"format": "int32"
},
"month": {
"type": "string",
"enum": ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"]
},
"monthValue": {
"type": "integer",
"format": "int32"
},
"nano": {
"type": "integer",
"format": "int32"
},
"second": {
"type": "integer",
"format": "int32"
},
"year": {
"type": "integer",
"format": "int32"
}
}
},
我试过了
'A. @ApiModelProperty(dataType = "java.lang.String", example = "17-03-2019 22:18:59", notes = "Birthdaytime desc")
B. @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MM-dd-yyyy hh:mm:ss")'
在 A 中,元素仅在 yaml 中定义为字符串,缺少“格式:日期时间”,如下所示。
SampleClass:
properties:
dateOfBirth:
type: string
需要什么调整才能为此创建一个完美的swegger?我需要这个
SampleClass:
properties:
dateOfBirth:
type: string
format: date-time .
解决方案
只需在您的 LocalDateTime 字段上添加以下注释即可在 swagger 定义中格式化日期时间:
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", shape = Shape.STRING)
@ApiModelProperty(required = true, example = "2021-08-20T00:00:00")
推荐阅读
- keras - 使用 TensorFlow 之类的 Keras 进行 gpu 计算
- apache-spark - 数据列 inputCol 尚未分析,无法在此数据帧上运行 TF
- oracle - PL/SQL 错误处理后继续执行
- ios - 无法将选定行的值分配给变量
- batch-file - 使用批处理脚本递归比较2个文件夹的内容,并将差异复制到第三个文件夹
- testing - TFS Web 界面是否支持 Internet Explorer 11 中的测试管理
- excel - 无法自动刷新 HPE 的 excel SFDC 连接器
- java - 插入服务中的房间而不更新活动中的 LiveData
- python - 在管道中拟合参数:pipeline.set_params() vs **params inside estimator
- javascript - 在 url 中使用正则表达式模式获取搜索词