根据 JSON Schema C# 验证 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19544183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Validate JSON against JSON Schema C#
提问by Shaun Groenewald
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 模式验证 JSON 结构?我查看并找到了 JSON.Net 验证,但这并没有达到我想要的效果。
JSON.netdoes:
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
This validates to 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);
This also validates to true
这也验证为真
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);
Only this validates to false.
只有这验证为假。
Ideally I would like it to Validate that there are no fields aka name
in there that shouldn't be in there aka surname
.
理想情况下,我希望它验证那里没有name
不应该在那里的字段aka surname
。
采纳答案by Andy Robinson
I think that you just need to add
我认为你只需要添加
'additionalProperties': false
to your schema. This will stop unknown properties being provided.
到您的架构。这将停止提供未知的属性。
So now your results will be:- True, False, False
所以现在你的结果将是:- True, False, False
test code....
测试代码....
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);
}
output :-
输出 :-
True
False
False
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:-
您还可以将 "required":true 添加到必须提供的字段中,这样您就可以返回包含缺少/无效字段详细信息的消息:-
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.
回答by Liran
Ok i hope this will help.
好的,我希望这会有所帮助。
This is your schema:
这是您的架构:
public class test
{
public string Name { get; set; }
public string ID { get; set; }
}
This is your validator:
这是您的验证器:
/// <summary>
/// extension that validates if Json string is copmplient to TSchema.
/// </summary>
/// <typeparam name="TSchema">schema</typeparam>
/// <param name="value">json string</param>
/// <returns>is valid?</returns>
public static bool IsJsonValid<TSchema>(this string value)
where TSchema : new()
{
bool res = true;
//this is a .net object look for it in msdn
JavaScriptSerializer ser = new JavaScriptSerializer();
//first serialize the string to object.
var obj = ser.Deserialize<TSchema>(value);
//get all properties of schema object
var properties = typeof(TSchema).GetProperties();
//iterate on all properties and test.
foreach (PropertyInfo info in properties)
{
// i went on if null value then json string isnt schema complient but you can do what ever test you like her.
var valueOfProp = obj.GetType().GetProperty(info.Name).GetValue(obj, null);
if (valueOfProp == null)
res = false;
}
return res;
}
And how to use is:
使用方法是:
string json = "{Name:'blabla',ID:'1'}";
bool res = json.IsJsonValid<test>();
If you have any question please ask, hope this helps, please take into consideration that this isn't a complete code without exception handling and such...
如果您有任何问题,请询问,希望这会有所帮助,请考虑到这不是没有异常处理等的完整代码......