我认为您只需要添加
'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);}输出:-
TrueFalseFalse
您还可以在必须提供的字段中添加“ 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.



