针对JSON Schema C#validationJSON
有没有办法针对该结构的JSON模式validationJSON结构? 我已经查看并发现JSON.Netvalidation但这不符合我的要求。
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);
只有这个validation为false。
理想情况下,我希望它validation在那里没有name
也不属于surname
字段。
我认为你只需要添加
'additionalProperties': 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添加到必须提供的字段中,以便您可以返回包含缺失/无效字段详细信息的消息: –
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.
好的,我希望这会有所帮助。
这是你的架构:
public class test { public string Name { get; set; } public string ID { get; set; } }
这是你的validation器:
/// /// extension that validates if Json string is copmplient to TSchema. /// /// schema /// json string /// is valid? public static bool IsJsonValid(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 (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; }
如何使用是:
string json = "{Name:'blabla',ID:'1'}"; bool res = json.IsJsonValid();
如果您有任何疑问,请询问,希望这有帮助,请考虑到这不是一个完整的代码,无需例外处理等…