Fixing JSON Date serialization from .Net web method

ajax c# entity-framework serialization webforms


I am currently working on a project where I am sending a .Net type via ajax to a client application via ajax. I have no issues with the object being serialized and set to the client.

I run into issues when I take the exactly same object and post it back to the server via a web method with the following error: /Date(1373950800000)/ is not a valid value for DateTime. Which is pretty annoying as that is how Microsoft gave it to me, but that's besides the point.

Does anyone have a quick fix for this? I want a seamless way this can be accomplished without having to change the object right before returning it from the ajax call.

8/2/2013 4:52:13 PM

Accepted Answer

Your issue comes down to the server-side JavaScript serializer you are using; either JsonDataContractSerializer (default serializer for ASP.NET MVC) or NewtonSoft Json Serializer (default serializer for ASP.NET Web API).

For a visual example of this date mangling issue as well as possible solutions, check out JSON Dates are Different in ASP.NET MVC and Web API.

8/2/2013 5:08:02 PM

Popular Answer

Handle the DateFormat while serialization following code will resolve your problem

   JsonConvert.SerializeObject(yourobject, Formatting.Indented,
                    new JsonSerializerSettings
                         DateFormatHandling = DateFormatHandling.IsoDateFormat

It will result the dates in 2009-02-15T00:00:00Z format

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow