Dealing with Null DateTime returned by JSON

Working on the Spektrix API integration for Hull Truck Theatre highlighted an issue with JSON data when the receiving model required a DateTime field.


The API unit tests showed a fail when trying to convert Null to a DateTime property.


My first approach was to make the properties nullable - DateTime?, however this created problems down the line in consumption of the value as the consuming code was not expecting a nullable field value.


The answer came closer to the API receiving layer - at the point where the JSON is deserialized. At this level we can either create a global approach to handling null values OR we can decorate the model properties individually to ignore null values as appropriate. I chose the latter approach and decorated the model properties required with the following attribute.


    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public DateTime MyDateField { get; set; }


And for reference - the global settings approach


    var customJsonSerializerSettings = new JsonSerializerSettings
         NullValueHandling = NullValueHandling.Ignore
    var myObjectJsonModel = JsonConvert.DeserializeObject(jsonString, customJsonSerializerSettings);


Where the consuming code then tries to read MyDateField if presents as a DateTime.MinValue and so all the consuming code still performs as expected in my case.


If you or your internal team need any consultation or support with .NET development or Umbraco CMS you can find out more here or call us on 0113 320 1302