DefaultValueHandling.Ignore and booleans

Aug 4, 2010 at 10:23 AM

Hi

I am using json.net 3.5 release 7 and have noticed that I can't get the example for default value handling to work.

Using the below code in a unit test the Paid property is always emitted in the serialized string.

Snippet

            Invoice invoice = new Invoice
            {
                Company = "Acme Ltd.",
                Amount = 50.0m,
                Paid = false,
                FollowUpDays = 30,
                FollowUpEmailAddress = string.Empty,
                PaidDate = null
            };

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

 

Snippet

    public class Invoice
    {
        public string Company { getset; }
        public decimal Amount { getset; }

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

        // customize default values
        [DefaultValue(30)]
        public int FollowUpDays { getset; }
        [DefaultValue("")]
        public string FollowUpEmailAddress { getset; }
    }

 

The result is: "{"Company":"Acme Ltd.","Amount":50.0,"Paid":false}"

 

If I add a DefaultValue(false) attribute to the Paid property it then doesn't emit the value, but it's not doing what I expect... am I missing something? Do I have to decorate each property with the DefaultValue attribute?


Thanks

 

Matt