DefaultValueAttribute |
This sample uses the DefaultValueAttribute to override the default value for a property and exclude it from serialization using DefaultValueHandling.
public class Customer { public string FirstName { get; set; } public string LastName { get; set; } [DefaultValue(" ")] public string FullName { get { return FirstName + " " + LastName; } } }
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); // {}