问题描述
我有一个JSON模式文件,其中一个属性定义为string
或null
:
I have JSON schema file where one of the properties is defined as either string
or null
:
"type":["string", "null"]
转换为YAML(与OpenAPI/Swagger结合使用)时,它将变为:
When converted to YAML (for use with OpenAPI/Swagger), it becomes:
type:
- 'null'
- string
但是Swagger编辑器显示错误:
but the Swagger Editor shows an error:
在OpenAPI中定义可为空的属性的正确方法是什么?
What is the correct way to define a nullable property in OpenAPI?
推荐答案
这取决于OpenAPI版本.
This depends on the OpenAPI version.
您的示例将在OpenAPI 3.1中有效(一旦发布并更新了工具以支持它).这个新的OAS版本将与JSON Schema草案2019-09兼容.
Your example will be valid in OpenAPI 3.1 (once it's released and tools are updated to support it). This new OAS version will be compatible with JSON Schema draft 2019-09.
type:
- 'null' # Note the quotes around 'null'
- string
以上等同于:
oneOf:
- type: 'null' # Note the quotes around 'null'
- type: string
type: string
+ nullable: true
(如在OAS 3.0.x中一样,请参见下文)也可以使用,但是为了支持JSON Schema的'null'
类型,将不推荐使用nullable
关键字.
type: string
+ nullable: true
(as in OAS 3.0.x, see below) will also work, but the nullable
keyword is going to be deprecated in favor of JSON Schema's 'null'
type.
可空字符串定义如下:
type: string
nullable: true
这与JSON Schema语法不同,因为高达3.0.x的OpenAPI版本使用其自己的 JSON模式的风味(扩展子集").区别之一是type
必须是单个类型,并且不能是类型列表.也没有'null'
类型.而是使用 nullable
关键字用作type
修饰符,以允许null
值.
This is different from JSON Schema syntax because OpenAPI versions up to 3.0.x use their own flavor of JSON Schema ("extended subset"). One of the differences is that the type
must be a single type and cannot be a list of types. Also there's no 'null'
type; instead, the nullable
keyword serves as a type
modifier to allow null
values.
OAS2不支持'null'
作为数据类型,因此您很不走运.您只能使用type: string
.但是,即使null不属于OpenAPI 2.0规范的一部分,某些工具也支持x-nullable: true
作为供应商扩展.
OAS2 does not support 'null'
as the data type, so you are out of luck. You can only use type: string
. However, some tools support x-nullable: true
as a vendor extension, even though nulls are not part of the OpenAPI 2.0 Specification.
请考虑迁移到OpenAPI v.3,以获取对null的适当支持.
Consider migrating to OpenAPI v. 3 to get proper support for nulls.
这篇关于如何在OpenAPI(Swagger)中定义可以为字符串或null的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!