如何在Open API(Swagger)中为HashMap的键提供示例?
问题与解决方案
目标JSON结构
{ "a_property": [ { "key": "foo", "property_1": "a string 1", "property_2": "a string 2" }, { "key": "bar", "property_1": "a string 3", "property_2": "a string 4" } ] }
问题
尝试为上述JSON编写Schema时,使用additionalProperties无法在Schema中指定键的示例。
解决方案
additionalProperties本身不支持直接定义键的示例,但可以通过两种方式实现需求:
1. 给对象添加完整示例结构
在Schema的对象层级添加examples字段,直接给出包含目标示例键的完整JSON结构,清晰展示键的示例:
{ "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "a_property": { "type": "array", "items": { "type": "object", "properties": { "key": { "type": "string", "examples": ["foo", "bar"] }, "property_1": { "type": "string" }, "property_2": { "type": "string" } }, "required": ["key", "property_1", "property_2"], "additionalProperties": { "type": "string" }, // 在这里给出包含示例键的完整对象示例 "examples": [ { "key": "foo", "property_1": "a string 1", "property_2": "a string 2", "demo_key_1": "demo value 1", "demo_key_2": "demo value 2" } ] } } }, "required": ["a_property"] }
2. 使用patternProperties匹配键模式+说明示例
如果你的动态键有特定命名规则,可以用patternProperties替代additionalProperties,同时在描述中明确键的示例:
{ "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "a_property": { "type": "array", "items": { "type": "object", "properties": { "key": { "type": "string", "examples": ["foo", "bar"] }, "property_1": { "type": "string" }, "property_2": { "type": "string" } }, "required": ["key", "property_1", "property_2"], // 匹配小写字母组成的键,同时说明示例 "patternProperties": { "^[a-z]+$": { "type": "string", "description": "示例键:foo、bar、demo" } }, // 禁止不符合pattern的额外属性(可选) "additionalProperties": false } } }, "required": ["a_property"] }
内容的提问来源于stack exchange,提问作者DP2002
相关产品推荐
相关产品推荐

