问题描述
有没有办法在models部分定义HashMap或Generic Object类型?我有一个返回产品的 REST 服务,这些产品可以有不同的选择.options 属性基本上是一个 HashMap,其中 id 是选项名称,其值是选项值.
Is there any way to define a HashMap or Generic Object type in the models section?I have a REST service that returns products and those products can have different options. The options property are basically a HashMap, where the id is the option name and its value is the option value.
推荐答案
是的,这是可能的.
在 OpenAPI (fka. Swagger) 2.0 和 3.0 中,哈希图始终是 映射:
In OpenAPI (fka. Swagger) 2.0 and 3.0, a hashmap is always a <string, something>
map:
- 键总是一个字符串,不需要定义.
- 值类型是您想要的,并使用
additionalProperties
定义.
假设您想描述一个 哈希映射,如下所示:
Let's say you want to describe a <string, string>
hashmap like this one:
{
"key1": "value1",
"key2": "value2"
}
相应的 OpenAPI 2.0 定义为:
The corresponding OpenAPI 2.0 definition will be:
definitions:
StringStringMap:
type: object
additionalProperties:
type: string
在 OpenAPI 3.0 中,定义为:
In OpenAPI 3.0 the definition will be:
components:
schemas:
StringStringMap:
type: object
additionalProperties:
type: string
像这样的 哈希图
{
"key1": {"someData": "data", "someOtherData": true},
"key2": {"someData": "data2", "someOtherData": false}
}
将在 OpenAPI 2.0 中以这种方式定义:
will be defined this way in OpenAPI 2.0:
definitions:
ComplexObject:
type: object
properties:
someData:
type: string
someOtherData:
type: boolean
StringObjectMap:
type: object
additionalProperties:
$ref: "#/definitions/ComplexObject"
在 OpenAPI 3.0 中:
and in OpenAPI 3.0:
components:
schemas:
ComplexObject:
type: object
properties:
someData:
type: string
someOtherData:
type: boolean
StringObjectMap:
type: object
additionalProperties:
$ref: "#/definitions/ComplexObject"
我刚刚在 我的 OpenAPI(fka Swagger 教程)的第 4 部分.
OpenAPI (fka. Swagger) 规范也简要解释了这一点.
这篇关于Swagger HashMap 属性类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!