Using .NET JavaScriptSerializer.Deserialize with DateTime from client

Viewed 9173

I'm using the JavaScriptSerializer.Deserialize<>() method to convert JSON I receive from the client into a custom C# class. One of the properties of that class is a DateTime. Currently the Deserialize<>() method throws an error, saying

"(my date string)" is not a valid value for DateTime.

I've tried sending the date using several different formats, including ticks and other formats produced by the various built-in JavaScript Date() methods, but none of them have worked.

Exactly what format is the Deserialize<>() method expecting in order to parse it into a .NET DateTime?

5 Answers

After receving the error

/Date(1347992529530)/ is not a valid value for DateTime.

using the replace suggested by @Luis Perez worked for me.

var data = ko.toJSON({ objext: obj});
$.ajax({
    url: "/API/API.asmx/SaveObject",
    type: "POST",
    dataType: "json",
    contentType: "application/json; char-utf8;",
    data: data.replace(/\/Date/g, "\\\/Date").replace(/\)\//g, "\)\\\/"),
    success: function (r) {},
    error: function (e) {},
    complete: function () {}
});

I would suggest using JsonConvert.DeserializeObject<> instead.

Related