字典、哈希映射和关联数组
字典(也称为映射、哈希映射或关联数组)是一组键/值对。OpenAPI 允许您定义其中**键为字符串**的字典。要定义字典,请使用 type: object
并使用 additionalProperties
关键字来指定键/值对中值的类型。例如,一个字符串到字符串的字典,如下所示
1{ "en": "English", "fr": "French" }
使用以下 schema 定义
1type: object2additionalProperties:3 type: string
值类型
additionalProperties
关键字指定了字典中值的类型。值可以是基本类型(字符串、数字或布尔值)、数组或对象。例如,字符串到对象的字典可以定义如下
1type: object2additionalProperties:3 type: object4 properties:5 code:6 type: integer7 text:8 type: string
除了使用内联 schema,additionalProperties
还可以 $ref
另一个 schema
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!