Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

json.net

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'}");
    }    
}
like image 335
S.M.Amin Avatar asked Dec 06 '12 09:12

S.M.Amin


People also ask

What exceptions does Jsonconvert Deserializeobject throw?

Serialization or deserialization errors will typically result in a JsonSerializationException .

How does JSON deserialization work?

In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom . Net object. In the following code, it creates a JavaScriptSerializer instance and calls Deserialize() by passing JSON data. It returns a custom object (BlogSites) from JSON data.

What does Jsonconvert Deserializeobject do?

Deserializes the JSON to the specified . NET type. Deserializes the JSON to the specified . NET type using a collection of JsonConverter.

How do I deserialize a JSON file?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.


1 Answers

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' ").

like image 99
Alexander Bortnik Avatar answered Sep 20 '22 23:09

Alexander Bortnik