using Newtonsoft.Json;
namespace FAL.WebAPI2012.Controllers
{
public class Person
{
public int Id {get;set;}
public string FirstName {get;set;}
public string LastName {get;set;}
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Include,
NullValueHandling = NullValueHandling.Include)]
public DateTime? Dob { get; set; }
}
public class TestNullsController : ApiController
{
// GET api/<controller>
public Person Get()
{
Person myPerson = new Person() {
Dob = null, FirstName = "Adrian", Id=1, LastName="Bobby"
};
return myPerson;
}
}
}
As you can see, my Dob field is set to null but the result is the following
{ "Id":1, "FirstName":"Adrian", "LastName":"Bobby" }
and Dob is not serialized to null which I need it to be!
(I have tested that JsonProperty is setting other attributes like name and it changes the JSON output perfectly. I just can’t get the nullable property to be serialized.
Also, I have tested Json.Net (see answer below), so my thinking is that web api setup is overriding something somewhere, would be nice to know where).
I received this reply from a member of the web.api folk at Microsoft.
‘You’ll be glad to know this has been fixed since RC:
http://aspnetwebstack.codeplex.com/workitem/243
You can either upgrade to a newer package, or you can override our settings like this:
JsonFormatter.SerializerSettings = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Include };
Hope that helps’
So, all works with that update.