Click or drag to resize
Json.NETSerialization Error Handling
 

Json.NET supports error handling during serialization and deserialization. Error handling lets you catch an error and choose whether to handle it and continue with serialization or let the error bubble up and be thrown in your application.

Error handling is defined through two methods: the Error event on JsonSerializer and the OnErrorAttribute.

Error Event

The Error event is an event handler found on JsonSerializer. The error event is raised whenever an exception is thrown while serializing or deserializing JSON. Like all settings found on JsonSerializer, it can also be set on JsonSerializerSettings and passed to the serialization methods on JsonConvert.

Serialization Error Handling
 1List<string> errors = new List<string>();
 2
 3List<DateTime> c = JsonConvert.DeserializeObject<List<DateTime>>(@"[
 4      '2009-09-09T00:00:00Z',
 5      'I am not a date and will error!',
 6      [
 7        1
 8      ],
 9      '1977-02-20T00:00:00Z',
10      null,
11      '2000-12-01T00:00:00Z'
12    ]",
13    new JsonSerializerSettings
14    {
15        Error = delegate(object sender, ErrorEventArgs args)
16        {
17            errors.Add(args.ErrorContext.Error.Message);
18            args.ErrorContext.Handled = true;
19        },
20        Converters = { new IsoDateTimeConverter() }
21    });
22
23// 2009-09-09T00:00:00Z
24// 1977-02-20T00:00:00Z
25// 2000-12-01T00:00:00Z
26
27// The string was not recognized as a valid DateTime. There is a unknown word starting at index 0.
28// Unexpected token parsing date. Expected String, got StartArray.
29// Cannot convert null value to System.DateTime.

In this example we are deserializing a JSON array to a collection of DateTimes. On the JsonSerializerSettings a handler has been assigned to the Error event which will log the error message and mark the error as handled.

The result of deserializing the JSON is three successfully deserialized dates and three error messages: one for the badly formatted string ("I am not a date and will error!"), one for the nested JSON array, and one for the null value since the list doesn't allow nullable DateTimes. The event handler has logged these messages and Json.NET has continued on deserializing the JSON because the errors were marked as handled.

One thing to note with error handling in Json.NET is that an unhandled error will bubble up and raise the event on each of its parents. For example an unhandled error when serializing a collection of objects will be raised twice, once against the object and then again on the collection. This will let you handle an error either where it occurred or on one of its parents.

Parent Error Handling
 1List<string> errors = new List<string>();
 2
 3JsonSerializer serializer = new JsonSerializer();
 4serializer.Error += delegate(object sender, ErrorEventArgs args)
 5{
 6    // only log an error once
 7    if (args.CurrentObject == args.ErrorContext.OriginalObject)
 8    {
 9        errors.Add(args.ErrorContext.Error.Message);
10    }
11};

If you aren't immediately handling an error and only want to perform an action against it once, then you can check to see whether the ErrorEventArgs's CurrentObject is equal to the OriginalObject. OriginalObject is the object that threw the error and CurrentObject is the object that the event is being raised against. They will only equal the first time the event is raised against the OriginalObject.

OnErrorAttribute

The OnErrorAttribute works much like the other .NET serialization attributes that Json.NET supports. To use it you simply place the attribute on a method that takes the correct parameters: a StreamingContext and an ErrorContext. The name of the method doesn't matter.

Serialization Error Handling Attribute
 1public class PersonError
 2{
 3    private List<string> _roles;
 4
 5    public string Name { get; set; }
 6    public int Age { get; set; }
 7
 8    public List<string> Roles
 9    {
10        get
11        {
12            if (_roles == null)
13            {
14                throw new Exception("Roles not loaded!");
15            }
16
17            return _roles;
18        }
19        set { _roles = value; }
20    }
21
22    public string Title { get; set; }
23
24    [OnError]
25    internal void OnError(StreamingContext context, ErrorContext errorContext)
26    {
27        errorContext.Handled = true;
28    }
29}

In this example accessing the Roles property will throw an exception when no roles have been set. The HandleError method will set the error when serializing Roles as handled and allow Json.NET to continue serializing the class.

Serialization Error Handling Example
 1PersonError person = new PersonError
 2{
 3    Name = "George Michael Bluth",
 4    Age = 16,
 5    Roles = null,
 6    Title = "Mister Manager"
 7};
 8
 9string json = JsonConvert.SerializeObject(person, Formatting.Indented);
10
11Console.WriteLine(json);
12//{
13//  "Name": "George Michael Bluth",
14//  "Age": 16,
15//  "Title": "Mister Manager"
16//}
See Also