Tag Archives: json.net

Json Dates: Don’t cross the serializers!

With Json becoming the lingua franca of web data these days we are all spending a lot of time serializing and de-serializing objects across varying platforms.

While doing this recently I came across an interesting gotcha that is worth mentioning in case anyone else sees similar problems.

The issue is caused when serializing date objects into Json.

By choice I will always use Json.net (http://james.newtonking.com/projects/json-net.aspx) for serializing and de- serializing Json. It is many times faster than the default Microsoft option so is the obvious choice for dealing with objects of any reasonable size. However with smaller objects it is often easier to just use the default Microsoft objects.

Therefore I created an API call that returned Json using the simple call

return Json(o, JsonRequestBehavior.AllowGet);

and de-serialized this using a simple Json.net call

JsonConvert.DeserializeObject<IDictionary<int, Promotion>>(s);

This should have been straightforward, however the data returned included some date objects. The difficulty arose in how the two serializers handled daylight saving. Dates that were serialized as “30/6/2012 0:00” were being de-serialized as “29/6/2012 23:00”.

I didn’t have time to dig into the whys and wherefores of which was right and seeing as I had control of both ends of the transaction it was an easy fix to change the API call to be

return new ContentResult { Content = JsonConvert.SerializeObject(d), ContentType = "application/json" };

The dates are now in sync across both applications.

I’m interested in hearing if anyone has a better solution to this problem; leave your comments below.

Advertisements

Leave a comment

Filed under Code