问题
I have JSON schema file where one of the properties is defined as either string or null:
\"type\":[\"string\", \"null\"]
When converted to YAML (for use with OpenAPI/Swagger), it becomes:
type:
- \'null\'
- string
but the Swagger Editor shows an error:
Schema \"type\" key must be a string
What is the correct way to define a nullable property in OpenAPI?
回答1:
type as an array of types
type:
- string
- 'null'
is NOT valid in OpenAPI/Swagger (even though it's valid in JSON Schema). OpenAPI's type keyword requires a single type and cannot be an array of types.
Support for null depends on which version of OpenAPI you use:
In OpenAPI 3.0, use the nullable keyword to define nullable types:
type: string nullable: true # <----OpenAPI 2.0 does not support
nullas the data type, so if you use 2.0, you are out of luck. You can only usetype: string. That said, some tools supportx-nullable: trueas a vendor extension, even though nulls are not part of the OpenAPI 2.0 Specification.
来源:https://stackoverflow.com/questions/48111459/how-to-define-a-property-that-can-be-string-or-null-in-openapi-swagger