反序列化包含日期的json字符串

时间:2012-05-06 10:05:22

标签: c# json datetime deserialization

我一直在关于如何在json字符串中反序列化日期的一些帖子。

帖子提到对字符串进行替换以重新格式化日期部分。

json字符串如下所示:

"/Date(1336258800000)/\"

显然我需要做的是:

"new Date(1336258800000)"

问题是我一旦尝试替换,或者indexOf')/ \'它没有找到要替换的字符串(indexOf是-1)

谁能看到我做错了什么?

                    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;

这里是完整的json字符串:

"{\"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)/\"}"

更多信息,看看它们如何组合在一起:

代码背后的代码:

        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));
    }

我调用JSON.stringify来序列化存储对象的序列化,然后再发送回服务器,这是我做错了吗?

更新

这是工作代码:

string json = eventArgument.Replace( @"/Date(", "\\/Date(" ).Replace( @")/", ")\\/" );

2 个答案:

答案 0 :(得分:1)

尝试int index = json.IndexOf( @")/\\", 0 ); - 在斜杠

之前添加另一个斜杠

<强>更新

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

更新 - 解决方案

问题是初始字符串是/Date(1336258800000)/,而不是/Date(1336258800000)/\,因为最后一个斜杠是JSON中"字符的转义。 desiarization的格式应该是dirrerent,所以工作解决方案是

string json = eventArgument.Replace( @"/Date(", "\\/Date(" ).Replace( @")/", ")\\/" );

答案 1 :(得分:1)

我使用正则表达式,希望这不是问题。正则表达式检测/Date(NUMBER)/\并在正则表达式匹配中将NUMBER作为一个组,因此我使用它来替换dateTimeJson中与其构造函数中指定的正则表达式匹配的新日期(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);