NJsonSchema的dependentRequired与条件验证失效原因排查
问题
使用NJsonSchema进行JSON Schema验证时,类型、枚举等基础验证功能正常,但dependentRequired及if/then/else这类条件验证功能失效。例如示例代码中,包含credit_card字段但缺少billing_address的JSON本应判定为无效,但实际运行后被判定为有效,而在线JSON Schema验证工具可检测出该错误,请问原因是什么?遗漏了哪些配置?
示例代码如下:
static async Task Main() { // Define JSON Schema with dependentRequired validation string schemaJson = @" { ""type"": ""object"", ""properties"": { ""name"": { ""type"": ""string"" }, ""credit_card"": { ""type"": ""string"" }, ""billing_address"": { ""type"": ""string"" } }, ""dependentRequired"": { ""credit_card"": [""billing_address""] } }"; string validJson1 = @"{ ""name"": ""John Doe"" }"; // Valid JSON: No credit_card, so no billing_address required string invalidJson = @"{ ""name"": ""John Doe"", ""credit_card"": ""1234-5678-9876"" }"; // Invalid JSON: credit_card is present but billing_address is missing var schema = await NJsonSchema.JsonSchema.FromJsonAsync(schemaJson); // Load schema // Validate JSON cases Console.WriteLine("Valid JSON 1 (No credit card):"); ValidateJson(validJson1, schema); Console.WriteLine("\nInvalid JSON (Missing billing address but has credit card):"); ValidateJson(invalidJson, schema); } static void ValidateJson(string json, NJsonSchema.JsonSchema schema) { var validator = new JsonSchemaValidator(); var errors = validator.Validate(json, schema);// schema.Validate(json); - the same.. if (errors.Count == 0) { Console.WriteLine("✅ Valid JSON"); } else { Console.WriteLine("❌ Invalid JSON"); foreach (var error in errors) { Console.WriteLine($"Error: {error.Path} - {error.Kind}"); } } }
解决方案
问题核心是NJsonSchema默认使用的JSON Schema版本过低:
dependentRequired是JSON Schema Draft 7及后续版本才引入的特性,而NJsonSchema默认采用Draft 4(不支持该关键字),因此无法识别并执行这类条件验证规则。if/then/else同样需要Draft 7及以上版本支持,所以也会出现相同的失效问题。
解决方法有两种,任选其一即可:
方法1:加载Schema时指定版本
修改Schema加载代码,通过JsonSchemaSettings明确指定使用Draft 7及以上版本:
var schema = await NJsonSchema.JsonSchema.FromJsonAsync(schemaJson, new JsonSchemaSettings { SchemaType = JsonSchemaVersion.Draft7 });
方法2:在Schema JSON中声明版本
在你的Schema JSON最外层添加$schema关键字,指定对应的Draft版本,NJsonSchema会自动识别并使用该版本的验证规则:
{ "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "name": { "type": "string" }, "credit_card": { "type": "string" }, "billing_address": { "type": "string" } }, "dependentRequired": { "credit_card": ["billing_address"] } }
完成上述配置后,重新运行代码,dependentRequired规则会正常生效,包含credit_card但缺少billing_address的JSON会被正确判定为无效。
内容的提问来源于stack exchange,提问作者Dorian
相关产品推荐
相关产品推荐

