I have a controller action that effectively simply returns a JsonResult of my model. So, in my method I have something like the following:
return new JsonResult(myModel);
This works well, except for one problem. There is a date property in the model and this appears to be returned in the Json result like so:
'\/Date(1239018869048)\/'
How should I be dealing with dates so they are returned in the format I require? Or how do I handle this format above in script?
Just to expand on casperOne’s answer.
The JSON spec does not account for Date values. MS had to make a call, and the path they chose was to exploit a little trick in the javascript representation of strings: the string literal ‘/’ is the same as ‘\/’, and a string literal will never get serialized to ‘\/’ (even ‘\/’ must be mapped to ‘\\/’).
See http://msdn.microsoft.com/en-us/library/bb299886.aspx#intro_to_json_topic2 for a better explanation (scroll down to ‘From JavaScript Literals to JSON’)
A solution would be to just parse it out:
However I’ve heard that there is a setting somewhere to get the serializer to output
DateTimeobjects with thenew Date(xxx)syntax. I’ll try to dig that out.The second parameter of
JSON.parse()accepts areviverfunction where prescribes how the value originally produced by, before being returned.Here is an example for date:
See the docs of JSON.parse()