如何为包含Properties对象的对象定义JSON模式?

avi*_*iad 4 json jsonschema

我需要为对象创建一个JSON模式,该模式将包含java Properties对象作为其属性之一.嵌套的Properties对象将只是key = value的列表.键和值都是string类型.我找不到任何描述如何定义包含2种新类型的模式的文档.

应该是这样的:

{
"type": "object",
"name": "MyObj",
"properties": {
    "prop1": {
        "type": "string",
        "description": "prop1",
        "required": true
    },
    "props": {
        "type": "array",
        "items": {
            "type": "object"
            "properties": {
                "key": {
                    "type": "string",
                    "description": "key",
                    "required": true
                },
                "value": {
                    "type": "string",
                    "description": "the value",
                    "required": true
                }
            }
            "description": "the value",
            "required": true
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

}

clo*_*eet 21

您编写的模式(假设逗号已修复)描述了表单的数据:

{
    "prop1": "Some string property goes here",
    "props": [
        {"key": "foo", "value": "bar"},
        {"key": "foo2", "value": "bar2"},
        ...
    ]
}
Run Code Online (Sandbox Code Playgroud)

如果这是你想要的,那么你已经完成了.

但是,我确实想知道为什么你在数组中使用键/值对,当你可以使用带有字符串键的JSON对象时.使用additionalProperties关键字,您可以拥有一个架构:

{
    "type": "object",
    "name": "MyObj",
    "properties": {
        "prop1": {
            "type": "string",
            "description": "prop1"
        },
        "props": {
            "type": "object",
            "additionalProperties": {
                "type": "string",
                "description": "string values"
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这描述了一种数据格式,如:

{
    "prop1": "Some string property goes here",
    "props": {
        "foo": "bar",
        "foo2": "bar2"
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你想对键施加约束,你还可以使用patternProperties和additionalProperties: false。您也可以使用“模式”对值施加约束。 (2认同)