Blog Home  Home Feed your aggregator (RSS 2.0)  
.Net Jonesie - AJAX JSON DateTime Serialization
A simple programmers blog
 
# Monday, January 15, 2007
I've been doing a lot of fun JSON stuff lately using ASP.Net AJAX (aka ATLAS).  This really is Fun with a capital 'F' but I struck a small problem today.
 
Given the following C# class:
public class PageData {
 
    public string Name;
    public string Address;
    public DateTime DOB;
 
    ...
 
}
I serailize this to the page thus:
 
C#
 
    protected void getPageData() {
        PageData pd = new PageData("Peter Jones", "New Zealand", DateTime.Now());
        return "(" + JavascriptSerializer.Serializer(pd) + ")";
 
    }   
 
ASP:
 
    <DEFANGED script type="text/javascript">
        var pagedata = eval('<%= getPageData() %>');
 
    </script>
 
Now this works fine for all data types except DateTime.  When you serialize a DateTime you get a value in JSON like this:
 
    @7895678963897@
 
This is the number of milliseconds since 1 Jan 1970.  When this is de-serialized with eval() you just get a string. 
Instead of using eval() you need to use Sys.Serialization.JavaScriptSerializer.deserialize().
 
For reference see:  nikhilk.net and Hannes Preishuber
 
Update
 
This appears to have changed in the RTM release.  Dates are now serialized thus:  /Date(millseconds)/.  However, I cant get this to deserialize using Sys.Serialization.JavaScriptSerializer.deserialize() so have reverted to using a string in yyyymmddThhmm format, which Date.parse() will happily convert.
Monday, January 15, 2007 8:34:28 AM (New Zealand Daylight Time, UTC+13:00)  #    Comments [0]   General  | 
Comments are closed.
Copyright © 2012 Peter G Jones. All rights reserved.
DasBlog 'Portal' theme by Johnny Hughes.
Pick a theme: