In The craft
A Dirty Secret About JSON and .NET
In my last post I professed love for Json. I consider Json the new XML. Yet, everything is not all roses. I have found one of JSON’s dirty secrets: The current .Net (4.0) implementation (JavaScriptSerializer) converts all dates to UTC before the date is converted to Json. The offending code is displayed below:
private static void SerializeDateTime(DateTime datetime, StringBuilder sb, SerializationFormat serializationFormat)
{
if (serializationFormat == SerializationFormat.JSON)
{
sb.Append(""/Date(");
sb.Append((long) ((datetime.ToUniversalTime().Ticks - DatetimeMinTimeTicks) / 0x2710L));
sb.Append(")/"");
}
else
{
sb.Append("new Date(");
sb.Append((long) ((datetime.ToUniversalTime().Ticks - DatetimeMinTimeTicks) / 0x2710L));
sb.Append(")");
}
}
So what does this mean? It means every date that is serialized with JavaScriptSerialier will be converted to UTC.
Imagine this: You make an API call to the database. The results are returned to you in JSON. When reviewing the results with your boss, he asks why all the dates are wrong. WhaT? You check the database. They are correct in the database. What on earth?!?
What you did not know is the JavaScriptSerializer did you a favor and converted the dates to UTC without telling you. Thank you Mr. JavaScriptSerializer. Way to torpedo my credibility with my boss.