Reputation: 2253
I have a JSON object on client side that I want to get back on server side.
To do so, I have a hidden in which I put the stringified version of my object.
$("#<%=hidden.ClientID%>").val(JSON.stringify(obj));
Then, on server side, I try to deserialize it with JavaScriptSerializer.
My Problem : the stringified object contains a date and I can't parse it with de JavaScriptSerializer.
What I have done : Modify the date format to make it fit with the .Net format :
function FormatDate(date) {
if (typeof (date.getTime) != "undefined") {
return '\\/Date(' + date.getTime() + ')\\/'
}
return date;
}
Which seems to give a good format, but, when I use JSON.stringify on the object with the well formatted dates, it adds an extra backslash, so the JavaScriptSerializer still can't get it.
Any idea on how I could get it in a valid format in the hidden?
Upvotes: 3
Views: 467
Reputation: 4822
Old question but in case someone arrives here like me looking for a solution, found this that works: https://stackoverflow.com/a/21865563/364568
function customJSONstringify(obj) {
return JSON.stringify(obj).replace(/\/Date/g, "\\\/Date").replace(/\)\//g, "\)\\\/")
}
Upvotes: 1
Reputation: 519
I use the code below to fix the data after serializing.
var data = JSON.stringify(object);
data = data.replace(/\\\\/g, "\\");
Upvotes: 1
Reputation: 3498
I had the same Problem and
'\/Date(' + date.getTime() + ')\/';
works for me. You just have a double backslash instead of only one backslash.
Upvotes: 1