【问题标题】:Segregate the Handled errors from json Deserialization via Newtonsoft c#通过 Newtonsoft c# 将处理的错误与 json 反序列化分离
【发布时间】:2020-08-14 05:57:46
【问题描述】:

我在使用 NewtonSoft 反序列化 json 并将错误存储在列表中时处理错误,如 Newtonsoft Error handling 所示

问题是收到的所有错误,即。即使它的“解析错误”或“必需的成员丢失错误”是 JsonSerializationException 类型,我也无法按类型分离错误(我不想通过消息中包含的字符串操作来做到这一点)。

是否有任何其他可用的方法或库可供我用于此目的,即。获取 json 反序列化中的隔离错误列表?

【问题讨论】:

  • 你可以看看JsonSerializationExceptionInnerException 属性,也许它们会是不同的类型,所以你可以通过它排序/分离它们。但是无论如何你想对分离的异常做什么?
  • innerException 为空。有多个字段...隔离将允许概括错误,例如“缺少字段:字段 1、字段 2、字段 3”
  • 如果您想显示漂亮而精美的错误消息,您应该查看 Newtonsoft.Json(又名 Json.NET)提供的 validating JSON with JSON schemagenerating JSON schemas

标签: c# json json.net json-deserialization


【解决方案1】:

你可以这样开始:

        string json = File.ReadAllText("json1.json");
        var schemaGenerator = new JSchemaGenerator();
        var schema = schemaGenerator.Generate(typeof(List<Product>));
        var jToken = JToken.Parse(json);
        JsonValidationErrorSegregation errors = new JsonValidationErrorSegregation();

        jToken.Validate(schema, (sender, eventArgs) => {
            if (eventArgs.ValidationError.ErrorType == ErrorType.Required)
            {
                errors.RequiredErrors.Add(eventArgs.Message);
            }
            else if (eventArgs.ValidationError.ErrorType == ErrorType.Type)
            {
                errors.InvalidTypeErrors.Add(eventArgs.Message);
            }
            else
            {
                throw new System.Exception("Unhandled Error Type");
            }
        });

编码愉快,干杯!

【讨论】:

  • 这是一个好方法。但是,模式生成和验证会在代码中产生大量额外负载。我更喜欢更好的方法......这就是我避免使用 JSchema 的原因。此外,JSchema 并不是完全免费的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-13
  • 2017-10-16
  • 1970-01-01
相关资源
最近更新 更多