Click or drag to resize
Json.NET

DefaultValueHandling Enumeration

 
Specifies default value handling options for the JsonSerializer.

Namespace:  Newtonsoft.Json
Assembly:  Newtonsoft.Json (in Newtonsoft.Json.dll) Version: 11.0.1
Syntax
C#
[FlagsAttribute]
public enum DefaultValueHandling
Members
  Member nameValueDescription
Include0 Include members where the member value is the same as the member's default value when serializing objects. Included members are written to JSON. Has no effect when deserializing.
Ignore1 Ignore members where the member value is the same as the member's default value when serializing objects so that it is not written to JSON. This option will ignore all default values (e.g. null for objects and nullable types; 0 for integers, decimals and floating point numbers; and false for booleans). The default value ignored can be changed by placing the DefaultValueAttribute on the property.
Populate2 Members with a default value but no JSON will be set to their default value when deserializing.
IgnoreAndPopulate3 Ignore members where the member value is the same as the member's default value when serializing objects and set members to their default value when deserializing.
Examples
DefaultValueHandling Class
public class Invoice
{
    public string Company { get; set; }
    public decimal Amount { get; set; }

    // false is default value of bool
    public bool Paid { get; set; }
    // null is default value of nullable
    public DateTime? PaidDate { get; set; }

    // customize default values
    [DefaultValue(30)]
    public int FollowUpDays { get; set; }

    [DefaultValue("")]
    public string FollowUpEmailAddress { get; set; }
}
DefaultValueHandling Ignore Example
Invoice invoice = new Invoice
{
    Company = "Acme Ltd.",
    Amount = 50.0m,
    Paid = false,
    FollowUpDays = 30,
    FollowUpEmailAddress = string.Empty,
    PaidDate = null
};

string included = JsonConvert.SerializeObject(invoice,
    Formatting.Indented,
    new JsonSerializerSettings { });

// {
//   "Company": "Acme Ltd.",
//   "Amount": 50.0,
//   "Paid": false,
//   "PaidDate": null,
//   "FollowUpDays": 30,
//   "FollowUpEmailAddress": ""
// }

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

// {
//   "Company": "Acme Ltd.",
//   "Amount": 50.0
// }
See Also