Click or drag to resize
Json.NETDefaultValueAttribute
 

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

Sample
Types
 1public class Customer
 2{
 3    public string FirstName { get; set; }
 4    public string LastName { get; set; }
 5
 6    [DefaultValue(" ")]
 7    public string FullName
 8    {
 9        get { return FirstName + " " + LastName; }
10    }
11}
Usage
 1Customer customer = new Customer();
 2
 3string jsonIncludeDefaultValues = JsonConvert.SerializeObject(customer, Formatting.Indented);
 4
 5Console.WriteLine(jsonIncludeDefaultValues);
 6// {
 7//   "FirstName": null,
 8//   "LastName": null,
 9//   "FullName": " "
10// }
11
12string jsonIgnoreDefaultValues = JsonConvert.SerializeObject(customer, Formatting.Indented, new JsonSerializerSettings
13{
14    DefaultValueHandling = DefaultValueHandling.Ignore
15});
16
17Console.WriteLine(jsonIgnoreDefaultValues);
18// {}