gpt4 book ai didi

java - 为 Java LocalDateTime 生成正确的 swagger 规范

转载 作者:行者123 更新时间:2023-12-03 11:20:24 25 4
gpt4 key购买 nike

我正在尝试在 Spring Boot 应用程序中使用 Swagger 注释从 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;
....
}'

我想为此创建正确的 swagger yaml speck。当我访问自动提供 yaml 的 swagger UI 时,我期望以下内容。

请注意 dateOfBirth 是一个 Java 8 LocalDateTime 类。但是根据 swagger 规范( https://swagger.io/specification/ 查找数据类型部分),yaml 中的日期应该是类型:'string' 和格式:日期时间。
 '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")

关于java - 为 Java LocalDateTime 生成正确的 swagger 规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55555764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com