Friday, August 12, 2011

ASP.NET MVC JSON strings

Although JSON is a great and simple format, I’m not a big fan of the way dates are represented.  If you have a look at a JSONResult in ASP.NET MVC you’ll probably see some data like this:

{“result”:[{"ProductId":"21329023","OrderDate":"\/Date(1296824894700”}]}

You’ll see that the Date is:

\/Date(1296824894700)\/

Not very JavaScript friendly. We tried a lot of different approaches in getting something more useful back from our action results(including just using strings instead of datetimes). In the end we decided to use the  jQuery’s dataFilter property. The dataFilter function is used to sanitize a response from a web server.  We ended up with the following small jQuery code:

$.ajaxSettings.dataFilter = function (data, type) {
if (type === 'json') {
data = data.replace(/\/Date\((.*?)\)\//gi,
function (fullMatch, $1, $2, $3) {
try {
return $1 + new Date(parseInt($2.substr(6))).toUTCString() + $3;
}
catch (e) { }
return $1 + $2 + $3;
});
}
return data;
};


This method uses a regular expression to look for the various elements that represent a Date in Microsoft JSON serialization format. The resulting date is reformatted to a human readable string. This format can be understood by other JavaScript components like for example the jQuery jqGrid.



Anyone with a better alternative?

1 comment:

Anonymous said...

http://blog.activa.be/index.php/2010/03/handling-dates-in-json-responses-with-jquery-1-4-the-easy-way/

http://stackoverflow.com/questions/206384/how-to-format-a-json-date