c# - 通过 Newtonsoft c# 将处理的错误与 json 反序列化分离
问题描述
我在使用 NewtonSoft 反序列化 json 并将错误存储在列表中时处理错误,如Newtonsoft 错误处理中所示
问题是收到的所有错误,即。即使它的“解析错误”或“必需的成员丢失错误”是 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");
}
});
快乐的编码,干杯!
推荐阅读
- javassist - 使用 javassist 时找不到 getDeclaredMethod
- python - Python dict 项目匹配返回 TypeError: 'int' object is not iterable
- reactjs - Alan AI 参考错误,未定义的 TypeError 编号
- android - 如何在 ViewPager2 中重置 ViewHolder 的视图状态,一旦它不再可见?
- mysql - 有没有人遇到过 pgloader 成功创建表但没有数据迁移的问题?
- ios - 在 SwiftUI 中调整滚动视图的内容
- vb.net - 我有许多 VB 2017 桌面应用程序。我们使用 Setup and Deployment 项目来构建安装 msi。它不再创建 MSI
- javascript - 如何查看 Realm ObjectId 是否等于字符串(JavaScript)
- r - 运营商怎么样!!在 R 包 rlang 中被定义?
- react-native - 如何在 React Native 中使用 Product Flavors res 值?