Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixing JSON Date serialization from .Net web method

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.

like image 564
Justin Avatar asked Aug 02 '13 16:08

Justin


3 Answers

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.

like image 93
Karl Anderson Avatar answered Nov 17 '22 15:11

Karl Anderson


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

like image 43
Rao khurram adeel Avatar answered Nov 17 '22 14:11

Rao khurram adeel


This one will help you with the error: click me

var yourDateTimeObject = ...
var converter = new IsoDateTimeConverter();

string isoDateTime = Newtonsoft.Json.JsonConvert.SerializeObject(yourDateTimeObject, converter);
like image 2
kul_mi Avatar answered Nov 17 '22 14:11

kul_mi