Click or drag to resize
Json.NET

ErrorHandlingAttribute

 

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

Sample
Types
public class Employee
{
    private List<string> _roles;

    public string Name { get; set; }
    public int Age { get; set; }

    public List<string> Roles
    {
        get
        {
            if (_roles == null)
            {
                throw new Exception("Roles not loaded!");
            }

            return _roles;
        }
        set { _roles = value; }
    }

    public string Title { get; set; }

    [OnError]
    internal void OnError(StreamingContext context, ErrorContext errorContext)
    {
        errorContext.Handled = true;
    }
}
Usage
Employee person = new Employee
{
    Name = "George Michael Bluth",
    Age = 16,
    Roles = null,
    Title = "Mister Manager"
};

string json = JsonConvert.SerializeObject(person, Formatting.Indented);

Console.WriteLine(json);
// {
//   "Name": "George Michael Bluth",
//   "Age": 16,
//   "Title": "Mister Manager"
// }