字典、哈希映射和关联数组
字典(也称为映射、哈希映射或关联数组)是一组键/值对。OpenAPI 允许您定义**键是字符串**的字典。要定义字典,请使用 type: object
并使用 additionalProperties
关键字指定键/值对中值的类型。例如,像这样的字符串到字符串的字典
1{ "en": "English", "fr": "French" }
是使用以下模式定义的
1type: object2additionalProperties:3 type: string
值类型
additionalProperties
关键字指定字典中值的类型。值可以是基本类型(字符串、数字或布尔值)、数组或对象。例如,字符串到对象的字典可以定义如下
1type: object2additionalProperties:3 type: object4 properties:5 code:6 type: integer7 text:8 type: string
除了使用内联模式,additionalProperties
可以 $ref
另一个模式
1components:2 schemas:3 Messages: # <---- dictionary4 type: object5 additionalProperties:6 $ref: "#/components/schemas/Message"7
8 Message:9 type: object10 properties:11 code:12 type: integer13 text:14 type: string
自由形式对象
如果字典值可以是任何类型(也称为自由形式对象),请使用 additionalProperties: true
1type: object2additionalProperties: true
这等效于
1type: object2additionalProperties: {}
固定键
如果字典有一些固定键,您可以将它们显式定义为对象属性,并将其标记为必需
1type: object2properties:3 default:4 type: string5required:6 - default7additionalProperties:8 type: string
字典内容示例
您可以使用 example
关键字来指定示例字典内容
1type: object2additionalProperties:3 type: string4example:5 en: Hello!6 fr: Bonjour!