繁体   English   中英

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

[英]deserialize json string containing date

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

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

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

标记/ 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来序列化存储对象的序列化,这是我做错了什么?

UPDATE

这是工作代码:

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

尝试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( @")/", ")\\/" );

我使用正则表达式,希望这不是问题。 正则表达式检测/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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM