跳到内容

字典、哈希映射和关联数组

字典(也称为映射、哈希映射或关联数组)是一组键/值对。OpenAPI 允许您定义**键是字符串**的字典。要定义字典,请使用 type: object 并使用 additionalProperties 关键字指定键/值对中值的类型。例如,像这样的字符串到字符串的字典

1
{ "en": "English", "fr": "French" }

是使用以下模式定义的

1
type: object
2
additionalProperties:
3
type: string

值类型

additionalProperties 关键字指定字典中值的类型。值可以是基本类型(字符串、数字或布尔值)、数组或对象。例如,字符串到对象的字典可以定义如下

1
type: object
2
additionalProperties:
3
type: object
4
properties:
5
code:
6
type: integer
7
text:
8
type: string

除了使用内联模式,additionalProperties 可以 $ref 另一个模式

1
components:
2
schemas:
3
Messages: # <---- dictionary
4
type: object
5
additionalProperties:
6
$ref: "#/components/schemas/Message"
7
8
Message:
9
type: object
10
properties:
11
code:
12
type: integer
13
text:
14
type: string

自由形式对象

如果字典值可以是任何类型(也称为自由形式对象),请使用 additionalProperties: true

1
type: object
2
additionalProperties: true

这等效于

1
type: object
2
additionalProperties: {}

固定键

如果字典有一些固定键,您可以将它们显式定义为对象属性,并将其标记为必需

1
type: object
2
properties:
3
default:
4
type: string
5
required:
6
- default
7
additionalProperties:
8
type: string

字典内容示例

您可以使用 example 关键字来指定示例字典内容

1
type: object
2
additionalProperties:
3
type: string
4
example:
5
en: Hello!
6
fr: Bonjour!

没有找到您要查找的内容?向社区提问
发现错误?让我们知道