3

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?

Phil-R
  • 2,193
  • 18
  • 21

3 Answers3

1

I had the same Problem and

'\/Date(' + date.getTime() + ')\/';

works for me. You just have a double backslash instead of only one backslash.

stefan.s
  • 3,489
  • 2
  • 30
  • 44
1

I use the code below to fix the data after serializing.

var data = JSON.stringify(object);
data = data.replace(/\\\\/g, "\\");
hebinda
  • 519
  • 6
  • 14
1

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, "\)\\\/")
}
Community
  • 1
  • 1