Click or drag to resize
Json.NET

DefaultValueAttribute

 

This sample uses the DefaultValueAttribute to override the default value for a property and exclude it from serialization using DefaultValueHandling.

Sample
Types
public class Customer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    [DefaultValue(" ")]
    public string FullName
    {
        get { return FirstName + " " + LastName; }
    }
}
Usage
Customer customer = new Customer();

string jsonIncludeDefaultValues = JsonConvert.SerializeObject(customer, Formatting.Indented);

Console.WriteLine(jsonIncludeDefaultValues);
// {
//   "FirstName": null,
//   "LastName": null,
//   "FullName": " "
// }

string jsonIgnoreDefaultValues = JsonConvert.SerializeObject(customer, Formatting.Indented, new JsonSerializerSettings
{
    DefaultValueHandling = DefaultValueHandling.Ignore
});

Console.WriteLine(jsonIgnoreDefaultValues);
// {}