首页 > 解决方案 > 通过 Newtonsoft c# 将处理的错误与 json 反序列化分离

问题描述

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

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

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

标签: c#jsonjson.netjson-deserialization

解决方案


你可以从这样的事情开始:

        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");
            }
        });

快乐的编码,干杯!


推荐阅读