问题描述
我正在处理错误,同时使用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");
}
});
编码愉快,加油!