根据 JSON Schema C# 验证 JSON [英] Validate JSON against JSON Schema C#
问题描述
有没有办法根据该结构的 JSON 模式验证 JSON 结构?我查看并发现了 JSON.Net 验证,但这并没有达到我想要的效果.
Is there a way to validate a JSON structure against a JSON schema for that structure? I have looked and found JSON.Net validate but this does not do what I want.
JSON.net 确实:
JsonSchema schema = JsonSchema.Parse(@"{
'type': 'object',
'properties': {
'name': {'type':'string'},
'hobbies': {'type': 'array'}
}
}");
JObject person = JObject.Parse(@"{
'name': 'James',
'hobbies': ['.NET', 'LOLCATS']
}");
bool valid = person.IsValid(schema);
// true
这验证为真.
JsonSchema schema = JsonSchema.Parse(@"{
'type': 'object',
'properties': {
'name': {'type':'string'},
'hobbies': {'type': 'array'}
}
}");
JObject person = JObject.Parse(@"{
'surname': 2,
'hobbies': ['.NET', 'LOLCATS']
}");
bool valid = person.IsValid(schema);
这也验证为真
JsonSchema schema = JsonSchema.Parse(@"{
'type': 'object',
'properties': {
'name': {'type':'string'},
'hobbies': {'type': 'array'}
}
}");
JObject person = JObject.Parse(@"{
'name': 2,
'hobbies': ['.NET', 'LOLCATS']
}");
bool valid = person.IsValid(schema);
仅此验证为 false.
Only this validates to false.
理想情况下,我希望它验证那里没有不应该在那里又名 surname
的字段,即 name
.
Ideally I would like it to Validate that there are no fields aka name
in there that shouldn't be in there aka surname
.
推荐答案
我认为你只需要添加
'additionalProperties': false
到您的架构.这将停止提供未知的属性.
to your schema. This will stop unknown properties being provided.
所以现在你的结果将是:-对、错、错
So now your results will be:- True, False, False
测试代码....
void Main()
{
var schema = JsonSchema.Parse(
@"{
'type': 'object',
'properties': {
'name': {'type':'string'},
'hobbies': {'type': 'array'}
},
'additionalProperties': false
}");
IsValid(JObject.Parse(
@"{
'name': 'James',
'hobbies': ['.NET', 'LOLCATS']
}"),
schema).Dump();
IsValid(JObject.Parse(
@"{
'surname': 2,
'hobbies': ['.NET', 'LOLCATS']
}"),
schema).Dump();
IsValid(JObject.Parse(
@"{
'name': 2,
'hobbies': ['.NET', 'LOLCATS']
}"),
schema).Dump();
}
public bool IsValid(JObject obj, JsonSchema schema)
{
return obj.IsValid(schema);
}
输出:-
True
False
False
您还可以将 "required":true 添加到必须提供的字段中,这样您就可以返回包含缺少/无效字段详细信息的消息:-
You could also add "required":true to the fields that must be supplied that way you can return a message with details of missing/invalid fields:-
Property 'surname' has not been defined and the schema does not allow additional properties. Line 2, position 19.
Required properties are missing from object: name.
Invalid type. Expected String but got Integer. Line 2, position 18.
这篇关于根据 JSON Schema C# 验证 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!