c# - Json.NET - 在反序列化期间在属性 setter 中抛出异常

标签 c# json.net

我使用属性 setter 来验证 C# 类中的输入并对无效输入抛出异常。我还使用 Json.NET 将 json 反序列化为对象。问题是我不知道在哪里捕获 setter 抛出的无效 json 值的异常。 JsonConvert.DeserializeObject 方法不会抛出异常。

public class A{
    private string a;

    public string number{
        get {return a;}
        set {
            if (!Regex.IsMatch(value, "^\\d+$"))
                throw new Exception();
            a = value;
        }
    }
}

public class Main
{
    public static void main()
    {
         // The Exception cannot be caught here.
         A a = JsonConvert.DeserializeObject<A>("{number:'some thing'}");
    }    
}

最佳答案

反序列化对象时需要订阅错误:

            JsonConvert.DeserializeObject<A>("{number:'some thing'}",
            new JsonSerializerSettings
            {
                Error = (sender, args) =>
                {
                    Console.WriteLine(args.ErrorContext.Error.Message);
                    args.ErrorContext.Handled = true;
                }
            });

如果您删除 args.ErrorContext.Handled = true 语句,您的 setter 中引发的异常将从 JsonConvert.DeserializeObject 方法中重新抛出。它将包装在 JsonSerializationException(“将值设置为‘number’的错误”)中。

关于c# - Json.NET - 在反序列化期间在属性 setter 中抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13740957/

相关文章:

c# - 如何在 C# 中执行原子写入/追加,或者如何使用 FILE_APPEND_DATA 标志打​​开文件?

c# - 如何使用数据 GridView (Winforms、C#)更新 MySQL 表?

.net - 如何将 JObject 反序列化为 .NET 对象

c# - 使用 Json.NET 将 JObject 转换为 Dictionary<string, string>

c# - 在面向 .NET Core 的类库包中使用 JsonConvert.DeserializeObject

c# - 在不卡住 GUI 的情况下向大型数据绑定(bind) ObservableCollection 添加/删除许多项目

c# - 动态标签 : Adding them using a dataset and checking if they exist

c# - 字符串数组中的 NULL

json - .NET NewtonSoft JSON 反序列化映射到不同的属性名称

.net - 如何调试 JSON 序列化错误?