Click or drag to resize
Json.NETErrorHandlingAttribute
 

This sample uses OnErrorAttribute to ignore the exception thrown setting the Roles property.

Sample
Types
 1public class Employee
 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}
Usage
 1Employee person = new Employee
 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// }