我使用属性 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/