根据http://jsonlint.com/和http://jsonschemalint.com/draft4/#,下面是一个有效的JSON模式。
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"required": ["results"],
"additionalProperties": false,
"properties": {
"results": {
"type": "string",
"oneOf": [
{ "result": "1" },
{ "result": "2" },
{ "result": "3" },
{ "result": "4" }
]
}
}
}
以下JSON在针对上述模式进行验证时报告一个错误(results is the wrong type
):
{
"results" : {
"result": "1"
}
}
谁能建议我如何解决这个错误?
看起来在这种情况下您想要的是enum
而不是oneOf
。下面是你如何定义你的模式。
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"required": ["results"],
"additionalProperties": false,
"properties": {
"results": {
"type": "object",
"properties": {
"result": {
"type": "string",
"enum": ["1", "2", "3", "4"]
}
}
}
}
}
但是,问题是如何正确使用oneOf
。oneOf
关键字应该是一个模式数组,而不是您在示例中使用的值。oneOf
中的一个且只有一个模式必须针对oneOf
子句验证的数据进行验证。我必须修改一下你的例子来说明如何使用oneOf
。本例允许result
为字符串或整数。
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"required": ["results"],
"additionalProperties": false,
"properties": {
"results": {
"type": "object",
"properties": {
"result": {
"oneOf": [
{
"type": "string",
"enum": ["1", "2", "3", "4"]
},
{
"type": "integer",
"minimum": 1,
"maximum": 4
}
]
}
}
}
}
}
根据您的模式定义,results
是object
的类型,但您提到的类型是String
。如果我改变类型为object
,它只是工作良好