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

时间:2013-10-14 14:13:23

标签: 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
        }
    }
}

}

2 个答案:

答案 0 :(得分:20)

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

{
    "prop1": "Some string property goes here",
    "props": [
        {"key": "foo", "value": "bar"},
        {"key": "foo2", "value": "bar2"},
        ...
    ]
}

如果这是您想要的,那么您已经完成了。

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

{
    "type": "object",
    "name": "MyObj",
    "properties": {
        "prop1": {
            "type": "string",
            "description": "prop1"
        },
        "props": {
            "type": "object",
            "additionalProperties": {
                "type": "string",
                "description": "string values"
            }
        }
    }
}

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

{
    "prop1": "Some string property goes here",
    "props": {
        "foo": "bar",
        "foo2": "bar2"
    }
}

答案 1 :(得分:0)

W3 schools (JSON Syntax),您可以阅读如何定义数组。

没有类似xsd for xml的架构,但是我找到了一种方法on json-schema.org。如果你能够,我会建议google-GSON library for JSON。您可以将键值存储为"id" : "value"并仅构建一个对象,其中包含所有必需的对:

{ "lang" : "EN" , "color" : "red" }

您发布的模型是incorect,您可以查看它on jsonlint.com 这是一个工作版本,我不确定modell是否符合预期。

{
    "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
                }
            }
        }
    ]
}
相关问题