Json.NET 架构:使用自定义 JSON 验证规则时的自定义错误类型

Json.NET Schema: Custom ErrorType when using a custom JSON validation rule

我正在使用 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

我的问题是:这种情况有解决方法吗?如何区分由我的自定义验证规则产生的错误以及它们之间的标准错误类型?

谢谢!

我在我打开的 Github issue 中收到了 Json.NET 架构作者的反馈。作者说:

Hi

ErrorType is an enum so there isn't a way to define new values at runtime. You will need to embed the information about what the error is in the message and test the content.

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