I use property setters to validate the input in a C# class and throw Exceptions on invalid inputs. I also use Json.NET to deserialize a json to an object. The problem is that I don’t know where to catch the exceptions for invalid json values which are thrown by the setters.
The Exception are not thrown from JsonConvert.DeserializeObject method.
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'}");
}
}
You need to subscribe to errors while deserializing your object:
If you remove
args.ErrorContext.Handled = truestatement, exception raised in your setter will be rethrown fromJsonConvert.DeserializeObjectmethod. It will be wrapped inJsonSerializationException(” Error setting value to ‘number’ “).