我正在使用 Swagger Core 2.0.2 for Java 生成 OpenAPI 文档。其中,我有以下类 SomeDTO
:
@Schema(name = "SomeDTO", description = "some description")
public class SomeDTO {
@Schema(description = "description of name")
private String name;
@Schema(required = true, description = "description of OtherDTO")
private OtherDTO otherDTO;
}
OtherDTO
说明如下:
public class OtherDTO {
@Schema(required = true)
private String someField;
private String someOtherField;
}
我的问题是 otherDTO
字段上方的 description
和 required
字段都没有任何效果。
生成的 openapi.json
如下所示:
"components": {
"schemas": {
"SomeDTO" : {
"type": "object",
"properties": {
"name": {
"type" : "string"
}
"otherDTO" : {
"$ref": "#/components/schemas/OtherDTO"
}
},
"description": "some description"
},
"OtherDTO": {
"required": ["someField"],
"type": "object",
"properties": {
"somefield": {
"type": "string"
},
"someOtherField": {
"type": "string"
}
}
}
}
}
我期望 SomeDTO
模式有一个包含 OtherDTO
的 required
数组,但事实并非如此。描述也丢失了。
我尝试了多种模式设置组合,但都无济于事。如果能帮助我理解我做错了什么,我将不胜感激。
提前致谢。
最佳答案
我已经找到了部分问题的解决方案。
问题是由于使用 $ref
元素时,sibling elements are ignored. 引起的。因此,与被引用元素相关的元素(description
、name
等)需要在被引用对象本身(OtherDTO
在上面的例子中)。在父对象中指定这些元素(例如 SomeDTO
)将忽略它们。
但是,引用元素中的架构元素似乎不会传播到父对象。因此,要使 otherDTO
成为 SomeDTO
中的必填字段,我需要将 requiredProperties = { "OtherDTO"})
添加到 SomeDTO
的架构。
这是更新后的代码:
SomeDTO
@Schema(name = "SomeDTO", description = "some description",
requiredProperties = { "OtherDTO" })
public class SomeDTO {
@Schema(description = "description of name")
private String name;
private OtherDTO otherDTO;
}
OtherDTO
@Schema(name = "OtherDTO", description = "Description of OtherDTO")
public class OtherDTO {
@Schema(required = true)
private String someField;
private String someOtherField;
}
但是,它并没有完全解决我的问题,因为我仍然无法弄清楚如何在 SomeDTO
中设置 otherDTO
的 description
>。但这让我更近了一步。
关于java - Swagger 忽略引用模式的模式属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51671883/