【问题标题】:Json.NET Schema: Custom ErrorType when using a custom JSON validation ruleJson.NET 架构:使用自定义 JSON 验证规则时的自定义 ErrorType
【发布时间】:2017-12-05 17:03:42
【问题描述】:

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

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

谢谢!

【问题讨论】:

    标签: c# .net json.net jsonschema


    【解决方案1】:

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

    ErrorType 是一个枚举,因此无法在 运行。您将需要嵌入有关错误的信息 在消息中并测试内容。

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

    【讨论】:

      猜你喜欢
      • 2021-08-03
      • 2017-07-25
      • 2017-04-11
      • 2018-02-18
      • 1970-01-01
      • 1970-01-01
      • 2011-04-10
      • 2019-02-12
      • 2016-11-22
      相关资源
      最近更新 更多