通过Newtonsoft C#将处理的错误与json反序列化隔离

问题描述

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

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

我是否可以为此目的使用其他任何方法或库。在json反序列化中获取隔离错误的列表?

解决方法

您可以从这样的内容开始:

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

编码愉快,加油!

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...