Json.NET架构:使用自定义JSON验证规则时的自定义ErrorType

时间:2017-12-05 17:03:43

标签: c# .net json.net jsonschema

我正在使用Json.NET Schema .NET库。

假设我已经定义了一个JSON模式,如:

JSchema schema = JSchema.Parse(@"{
    'type': 'object',
    'required' : ['name'],
    'properties': {
        'name': {'type':'string'},
        'roles': {'type': 'array'}
    }
}");

现在我正在验证JSON对象(请注意,我没有定义name属性):

JObject user = JObject.Parse(@"{
  'roles': ['Developer', 'Administrator']
}");

user.IsValid(schema, out IList<ValidationError> errors);

Debug.WriteLine(errors[0].ErrorType);

最后一行的输出为Required。这样我就知道运行时的特定错误类型,我可以通过编程方式根据此错误类型做出决定。

我的问题是,当我使用自定义验证规则时,我无法定义自定义错误类型。因此,我的所有自定义验证器都将创建一个错误实例,ErrorType属性等于Validator,如下例所示:

定义自定义验证规则:

class MyCustomValidator : JsonValidator
{
    public override void Validate(JToken value, JsonValidatorContext context)
    {
        var s = value.ToString();
        if (s != "valid")
        {
            context.RaiseError($"Text '{s}' is not valid.");
        }

    }

    public override bool CanValidate(JSchema schema)
    {
        return schema.Type == JSchemaType.String;
    }
} 

并使用自定义验证规则运行验证:

JSchema schema = JSchema.Parse(@"{
  'type': 'object',
  'required' : ['name'],
  'properties': {
    'name': {'type':'string'},
    'roles': {'type': 'array'}
  }
}");

JObject user = JObject.Parse(@"{
  'name': 'Ivalid',
  'roles': ['Developer', 'Administrator']
}");

schema.Validators.Add(new MyCustomValidator()); // adding custom validation rule

user.IsValid(schema, out IList<ValidationError> errors);

Debug.WriteLine(errors[0].ErrorType);

输出为Validator

我的问题是:这个案例有解决方法吗?如何区分我的自定义验证规则与其他标准错误类型之间产生的错误?

谢谢!

1 个答案:

答案 0 :(得分:1)

我收到了Json.NET Schema作者在Github issue打开的反馈意见。作者说:

  

您好

     

ErrorType是枚举,因此无法在以下位置定义新值   运行。您需要嵌入有关错误的信息   在邮件中并测试内容。

即:当前无法在运行时自定义错误类型属性。