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().
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.