0

I have been looking at a few posts on SO about how to deserialize a date in a json string.

The posts mention doing a replace on the string to reformat the Date parts.

the json string looks like this:

"/Date(1336258800000)/\"

apparently what I need to get to is this:

"new Date(1336258800000)"

The trouble is as soon as I try and to a replace, or indexOf ')/\' it doesnt find the string to replace (indexOf is -1)

can anyone see what im doing wrong?

                    JavaScriptSerializer jss = new JavaScriptSerializer();

                    //Fix an issue with Json Dates
                    string json = eventArgument.Replace( @"/Date(", "new Date(" ).Replace( @")/\", ")" );

                    int index = json.IndexOf( @")/\", 0 );

                    WorkPattern wp = jss.DeserializeObject( json ) as WorkPattern;

here is the full json string:

"{\"WorkPatternDays\":[{\"WorkPatternDayShifts\":[{\"WorkPatternDayShiftRates\":[{\"Duration\":8.5,\"Sequence\":0,\"WorkPatternDayShiftID\":186,\"WorkPatternDayShiftRateID\":105,\"Deleted\":false,\"UpdatedUser\":\"\",\"UpdatedDate\":\"/Date(1336258800000)/\"}],\"WorkPatternDayShiftBreaks\":[{\"PaidBreak\":true,\"Duration\":1,\"EndTime\":\"/Date(1336050000000)/\",\"StartTime\":\"/Date(1336046400000)/\",\"WorkPatternDayShiftID\":186,\"WorkPatternDayShiftBreakID\":284,\"Deleted\":false,\"UpdatedUser\":\"\",\"UpdatedDate\":\"/Date(1336258800000)/\"},{\"PaidBreak\":false,\"Duration\":0.25,\"EndTime\":\"/Date(1336058100000)/\",\"StartTime\":\"/Date(1336057200000)/\",\"WorkPatternDayShiftID\":186,\"WorkPatternDayShiftBreakID\":285,\"Deleted\":false,\"UpdatedUser\":\"\",\"UpdatedDate\":\"/Date(1336258800000)/\"}],\"Duration\":8.5,\"EndTime\":\"/Date(1336062600000)/\",\"StartTime\":\"/Date(1336032000000)/\",\"WorkPatternDayID\":186,\"WorkPatternDayShiftID\":186,\"Deleted\":false,\"UpdatedUser\":\"\",\"UpdatedDate\":\"/Date(1336258800000)/\"}],\"DayOfWeek\":1,\"DayOfWeekNumber\":1,\"WorkPatternID\":105,\"WorkPatternDayID\":186,\"Deleted\":false,\"UpdatedUser\":\"\",\"UpdatedDate\":\"/Date(1336258800000)/\"},{\"WorkPatternDayShifts\":[{\"WorkPatternDayShiftRates\":[],\"WorkPatternDayShiftBreaks\":[{\"PaidBreak\":true,\"Duration\":0.5,\"EndTime\":\"/Date(1336041000000)/\",\"StartTime\":\"/Date(1336039200000)/\",\"WorkPatternDayShiftID\":187,\"WorkPatternDayShiftBreakID\":286,\"Deleted\":false,\"UpdatedUser\":\"\",\"UpdatedDate\":\"/Date(1336258800000)/\"}],\"Duration\":5.5,\"EndTime\":\"/Date(1336046400000)/\",\"StartTime\":\"/Date(1336026600000)/\",\"WorkPatternDayID\":187,\"WorkPatternDayShiftID\":187,\"Deleted\":false,\"UpdatedUser\":\"\",\"UpdatedDate\":\"/Date(1336258800000)/\"}],\"DayOfWeek\":3,\"DayOfWeekNumber\":3,\"WorkPatternID\":105,\"WorkPatternDayID\":187,\"Deleted\":false,\"UpdatedUser\":\"\",\"UpdatedDate\":\"/Date(1336258800000)/\"}],\"WorkPatternName\":\"Naths Test Work Pattern\",\"WorkPatternID\":105,\"Deleted\":false,\"UpdatedUser\":\"\",\"UpdatedDate\":\"/Date(1336258800000)/\"}"

A bit more info to see how it all fits together:

code behind:

        public override void DataBind()
        {
            try
            {
                if ( this.WorkPattern != null )
                {
                    //Create a javascript serializer
                    JavaScriptSerializer jss = new JavaScriptSerializer();

                    //Get the serialised object as a json string
                    string json = jss.Serialize( this.WorkPattern );

                    //Run the jquery code
                    base.RunjQueryCode(
                        String.Format( "loadWorkPattern({0});", json ) );

                    jss = null;
                }
            }
            catch ( Exception )
            {

                throw;
            }
        }

 protected override void HandlePostbacks( string eventTarget, string eventArgument )
        {
            try
            {
                switch ( eventTarget )
                {
                    case "Save":

                        JavaScriptSerializer jss = new JavaScriptSerializer();

                        //Fix an issue with Json Dates
                        string json = eventArgument.Replace( @"/Date(", "new Date(" ).Replace( @")/\", ")" );

                        int index = json.IndexOf( @")/\\", 0 );

                        WorkPattern wp = jss.DeserializeObject( json ) as WorkPattern;


                        object o = jss.Deserialize<WorkPattern>( json );


                        break;
                    default: break;
                }

                base.HandlePostbacks( eventTarget, eventArgument );
            }
            catch ( Exception )
            {
                throw;
            }
        }

Markup / js:

function loadWorkPattern(jsonData) {

        //Store the work pattern
        _workPattern = jsonData;

        //Loop through the work pattern days
        $.each(_workPattern.WorkPatternDays, function (key, workPatternDay) {

            //Loop through each shift
            $.each(workPatternDay.WorkPatternDayShifts, function (key, workPatternShift) {
                addShift(workPatternShift, workPatternDay.DayOfWeekNumber);

                //Loop through each break
                $.each(workPatternShift.WorkPatternDayShiftBreaks, function (key, workPatternDayShiftBreak) {
                    addBreak(workPatternDayShiftBreak);
                });
            });
        });
    }

    function saveWorkPattern() {
        __doPostBack('Save', JSON.stringify(_workPattern));
    }

Im calling JSON.stringify to serialize the serialize the stored object before sending back to the server, is this what im doing wrong?

UPDATE

This is the working code:

string json = eventArgument.Replace( @"/Date(", "\\/Date(" ).Replace( @")/", ")\\/" );
WraithNath
  • 17,658
  • 10
  • 55
  • 82
  • Are you sending it to the client, or to the server? http://stackoverflow.com/questions/1224793/javascript-serialization-of-datetime-in-asp-net-is-not-giving-a-javascript-date/1227767#1227767 might be what you're after – Chris S May 06 '12 at 11:03
  • 1
    the correct format for deserialization that worked for me: `"\"\\/Date(1336302055941)\\/\""` – petrov.alex May 06 '12 at 11:03
  • @petrov.alex - OK, got it.. this works: string json = eventArgument.Replace( @"/Date(", "\\/Date(" ).Replace( @")/", ")\\/" ); – WraithNath May 06 '12 at 11:11
  • @petrov.alex - do you want to update your answer with my working code? – WraithNath May 06 '12 at 11:19

2 Answers2

1

Try int index = json.IndexOf( @")/\\", 0 ); - put another slash before the slash

Update

JavaScriptSerializer s = new JavaScriptSerializer();
string date = s.Serialize(DateTime.Now);
int index = date.IndexOf(@")\/", 0);
Console.WriteLine(index); // index = 21

Update - solution

The problem is the the initial string is /Date(1336258800000)/, but not /Date(1336258800000)/\ as the last slash is an escape of the " character in the JSON. And the format for the desiarization should be dirrerent, so the working solution is

string json = eventArgument.Replace( @"/Date(", "\\/Date(" ).Replace( @")/", ")\\/" );
petrov.alex
  • 1,089
  • 2
  • 12
  • 20
  • yeah tried int index = json.IndexOf( @")/\\", 0 ); and still -1. Its like it cant work out the )/\, I tried copying and pasting the code from the json but to see if it was a hidden character but not working – WraithNath May 06 '12 at 10:15
  • The output of the serialization is `"\/Date(1336300173708)\/"` (the order of slashes is different), so then this works `int index = date.IndexOf(@")\/")` – petrov.alex May 06 '12 at 10:29
  • I have added the json string that is passed into my method to the bottom of the question, the slashes are not in the order you specify?? – WraithNath May 06 '12 at 10:34
  • are you using JsonSerializer to get the json? I even can't just initialize the string with the order of dashes you are providing (if I am not using serializer to get the string) – petrov.alex May 06 '12 at 10:43
  • Hi, I have added some more info to the question, inlcuding the source for saving and loading. Im serializing with the Javascript serializer, and coverting back from javascript in the SaveWorkPattern() method by calling JSON.stringify - do you think this could be the problem? – WraithNath May 06 '12 at 10:45
  • actually I have looked a little bit carefully at you json: the last dash is escaping `'"'`, so I guess that initial string not `/Date(1336258800000)/\\`, but `/Date(1336258800000)/` – petrov.alex May 06 '12 at 10:48
  • Ah, I think thats it. the code should be: string json = eventArgument.Replace( @"/Date(", "Date(" ).Replace( @")/", ")" ); as the last \ is just an escape character. My problem now is that it still work serialize the date as Date(1336258800000)! – WraithNath May 06 '12 at 10:55
1

I used regular expressions, hope that's not a problem. The regex detect the /Date(NUMBER)/\ and gets the NUMBER as a group in the regular expression match so I use that to replace everything in the dateTimeJson that matches the regex specified in its constructor with new Date(NUMBER).

        //the source JSON
        string dateTimeJson = "/Date(1336258800000)/\\";
        string result = "";

        //you might want to do a quick IndexOf("Date") to make sure that there is a date
        //so you won't trouble yourselve with regex computation unnecessarily. performance?

        //find Date(NUMBER) matches and get the NUMBER then use it again with new Date in the 
        //call to replace
        System.Text.RegularExpressions.MatchCollection matches = null;
        System.Text.RegularExpressions.Regex regex = null;
        try
        {
            //at the end is one forwared slash for regex escaping \ and another is the \ that is escaped
            regex = new System.Text.RegularExpressions.Regex(@"/Date\(([0-9]*)\)/\\");
            matches = regex.Matches(dateTimeJson);
            string dateNumber = matches[0].Groups[1].Value;
            result = regex.Replace(dateTimeJson, "new Date(" + dateNumber + ")");
        }
        catch (Exception iii)
        {
            //MessageBox.Show(iii.ToString());
        }
        MessageBox.Show(result);
Lzh
  • 3,585
  • 1
  • 22
  • 36
  • Thanks MZN - i just got it working with the code I added at the bottom of my question. I wanted to use regex but got it working now so I dont want to touch it! – WraithNath May 06 '12 at 11:14