我似乎无法让 const 或 enum 作为 if-then-else JSON 模式验证的一部分工作。
当涉及 1 个验证值时,它们似乎可以互换。(参考)
这是我的 JSON 模式
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Test_Schema",
"description": "A schema for validating a test object",
"type": "object",
"additionalProperties": false,
"properties": {
"GeneralData": {
"type": "object",
"description": "Advsor and admin customer information",
"properties": {
"Name": {
"type": [ "string", "null" ],
"description": "Customer's advisor name"
},
"Age": {
"type": [ "string", "null" ],
"description": "Customer's advisor email"
},
"Location": {
"type": [ "string", "null" ],
"description": "The advisor's manager email'"
}
},
"required": [ "Name", "Location", "Age" ]
},
"ClientData": {
"type": "object",
"description": "Customer's information",
"additionalProperties": false,
"properties": {
"Title": {
"type": [ "string", "null" ]
},
"Forename": {
"type": [ "string", "null" ]
},
"Surname": {
"type": [ "string" ]
}
},
"required": [ "Title" ],
"if": {
"properties": {
"Forename": { "enum": [ "Soameonea" ] }
},
"required": [ "Forename" ]
},
"then": { "required": [ "Surname" ] },
"else": false
}
}
}
如果 Forename = "Someone" 我希望姓氏是必需的。
这是我序列化后的jsonObject:
{
"GeneralData": {
"Name": "Not Relevant",
"Age": "Not Relevant",
"Location": "Not Relevant"
},
"ClientData": {
"Title": "SomeTitle",
"Forename": "Someone",
"Surname": null
}
}
验证码:
internal void ValidateDataObjectOnSchema()
{
var dataObject = PopulateDataObject();
var json = JsonConvert.SerializeObject(dataObject);
var result = GetSchema().Validate(json);
var errors = result.Select(x =>
{
return new Errors() { Title = x.Property, Description = x.Schema.Description };
});
var i = errors;
}
internal JsonSchema GetSchema()
{
return JsonSchema.FromFileAsync("Test/testSchema.json").Result;
}
现在它仍然需要姓氏,即使枚举 Soameonea != 某人和我只需要标题。<== 问题 1
在 JSON 模式中,如果我设置 "Surname":{"type":["string","null]} 然后错误消失,如果我将 Forename 枚举的 if 条件更改为“某人”。<== 第 2 期
如果我用 Const 替换 Enum,我将无法获得不同的验证输出,因此,如果我能让一个工作,我确信另一个会跟随。
我找到了这个问题的几个答案(答案 1),我尝试实现同样的事情,但由于某种原因,它在我的情况下失败了。
我错过了什么?