【发布时间】:2014-04-09 10:21:45
【问题描述】:
我正在尝试检测用户是否将布尔值指定为字符串而不是真正的布尔值。 我正在测试 cmetsModule/enabled 以查看该值是否为 false,一次带引号,一次不带引号。
在线验证器:http://json-schema-validator.herokuapp.com/ 工作正常,并将失败标识为“在枚举中找不到实例值 (\"false\")(可能的值:[false])”。
但是,具有完全相同架构和 json 的 NewtonSoft Json(最新版本)将其定义为有效的 json。
架构:
{
"$schema":"http://json-schema.org/draft-04/schema#",
"description": "pages json",
"type": "object",
"properties":
{
"name": {"type":"string"},
"description": {"type":"string"},
"channel": {"type":"string"},
"commentsModule":{
"type": "object",
"anyOf":[
{ "$ref": "#/definitions/commentsModuleDisabled" }
]
}
},
"definitions":{
"commentsModuleDisabled":{
"required": [ "enabled" ],
"properties": {
"enabled": { "type": "boolean", "enum": [ false ] }
}
}
}
}
(使用 oneOf 得到相同的结果)
JSON:
{
"_id": {
"$oid": "530dfec1e4b0ee95f0f3ce11"
},
"pageId": 1234,
"pageType": "Show",
"name": "my name",
"description": "this is decription.” ",
"channel": "tech",
"commentsModule": {
"CaptionFieldDoesntExist": "Comments",
"enabled": "false"
},
"localInstance": "com",
"productionYear": "2014",
"navbarCaptionLink": "",
"logoAd": ""
}
Json.Net 代码(取自官网):
JsonSchema schema = JsonSchema.Parse(schemaJson);
JObject jsonToVerify = JObject.Parse(json);
IList<string> messages;
bool valid = jsonToVerify.IsValid(schema, out messages);
谢谢!
编辑: Json.Net 不支持 Json Schema v4,因此“定义”引用被忽略。
例如,在这种情况下,“标题”被检查最小长度为 1,并且为 0,但 Json.net 通过验证:
JSON
{
"_id": {
"$oid": "530dfec1e4b0ee95f0f3ce11"
},
"pageId": 1234,
"pageType": "Show",
"name": "another name",
"description": "description ",
"channel": "tech",
"commentsModule": {
"caption": "",
"enabled": true
},
"localInstance": "com",
"productionYear": "2014",
"navbarCaptionLink": "",
"logoAd": "" }
架构:
{
"$schema":"http://json-schema.org/draft-04/schema#",
"description": "pages json",
"type": "object",
"properties":
{
"name": {"type":"string"},
"description": {"type":"string"},
"channel": {"type":"string"},
"commentsModule":{
"type": "object",
"oneOf":[
{ "$ref": "#/definitions/commentsModuleDisabled" },
{ "$ref": "#/definitions/commentsModuleEnabled" }
]
}
},
"definitions":{
"commentsModuleDisabled":{
"required": [ "enabled" ],
"properties": {
"enabled": { "type": "boolean", "enum": [ false ] }
}
},
"commentsModuleEnabled":{
"required": [ "enabled", "caption" ],
"properties": {
"enabled": { "type": "boolean", "enum": [ true ] },
"caption": { "type": "string", "minLength": 1 }
}
}
} }
在这种情况下,来自在线工具的错误涉及两种模式的不匹配,并指的是最小长度要求:
"message" : "instance failed to match exactly one schema (matched 0 out of 2)"
... "message" : "string \"\" is too short (length: 0, required minimum: 1)",
【问题讨论】:
标签: json json.net jsonschema