Json.NET - Throwing Exception in a property setter during deserialization

c#, json.net

Solution

You need to subscribe to errors while deserializing your object:

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

If you remove `args.ErrorContext.Handled = true` statement, exception raised in your setter will be rethrown from `JsonConvert.DeserializeObject` method. It will be wrapped in `JsonSerializationException` (" Error setting value to 'number' ").

Problem

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'}"); } } ```

Original source