C# 如何使用json模式将字符串值验证为json文本中的数字?
我希望能够验证答案字段是否为数值。下面的片段是一个答案,它是一个更大的答案词典的一部分。每个答案都遵循一种通用格式,因此答案字段需要为字符串类型C# 如何使用json模式将字符串值验证为json文本中的数字?,c#,jsonschema,json-schema-validator,C#,Jsonschema,Json Schema Validator,我希望能够验证答案字段是否为数值。下面的片段是一个答案,它是一个更大的答案词典的一部分。每个答案都遵循一种通用格式,因此答案字段需要为字符串类型 "1": { "answer": "80035", "web_validated": true, "web_error_string": "", "server_error_string": ""
"1": {
"answer": "80035",
"web_validated": true,
"web_error_string": "",
"server_error_string": ""
},
这就产生了一个问题,因为我们正在使用JSON模式来验证答案字典。我们需要将应答字段验证为数值,这由字典必须遵循的JSON模板决定。下面是字典中一个问题的上述答案的模板片段
{
"id": "1",
"text": "KFI Number (Null required check)",
"type": "text",
"source": "phoebus",
"kfid_mapping": "KFID000",
"kfid_mapping_value": "",
"valid_answers": null,
"display_online": "readonly",
"required": "1",
"display_internal": "yes",
"hints": null,
"logic": null,
"rules": null,
"reason": null,
"conditional_explanation": null,
"conditional_question_id": null,
"conditional_question_answered": null,
"enabled": "1",
"order": "2",
"fk_section_id": "1",
"validated": false
}
我们用于验证问题id:1的当前JSON模式
"definitions": {
"question1-1": {
"type": "object",
"properties": {
"answer": {
"type": "string",
"minLength": 1
}
}
//other definitions removed
}
}
上面是这个问题答案的JSON模式定义
可能的解决方案:
我想看看JSON模式是否可以实现这一点?正如其他人提到的,您可以使用模式。下面是添加到示例中的语法:
"definitions": {
"question1-1": {
"type": "object",
"properties": {
"answer": {
"type": "string",
"pattern": "^\d+$",
"description": "Use regex to validate this string as a series of one or more digits"
}
}
//other definitions removed
}
}
好的,总是需要指定一个正则表达式,然后匹配“number”(可能像
[0-9]+
一样简单,但如果您愿意,您可以使用更高级的正则表达式)。就我个人而言,我更喜欢将这样的“语义”验证推迟到处理层,因为它提供了更多的灵活性。在这种情况下,通用验证器很少给出信息性错误消息,而缩短常规处理会剥夺您记录额外详细信息的机会(并改变您对正确信息的看法)。是的,上面的评论是正确的,唯一的方法是使用所述的正则表达式。如果您还有任何问题,请通过网站上的讨论链接加入JSON模式=]