Json.NET - 在反序列化期间在属性设置器中抛出异常

S.M*_*min 4 c# json.net

我使用属性设置器来验证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'}");
    }    
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*nik 9

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

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

如果删除args.ErrorContext.Handled = true语句,将从JsonConvert.DeserializeObject方法中重新引发setter中引发的异常.它将被包装JsonSerializationException("错误设置值为'数字'").