Home > Backend Development > C#.Net Tutorial > .net - processing of date and time in serialization and deserialization

.net - processing of date and time in serialization and deserialization

黄舟
Release: 2017-02-24 10:35:44
Original
1628 people have browsed it

承接上篇,现在我在类中加入一个日期时间类型的字段:

public  class Student
    {
       public string StudentId { get; set; }
       public string Name { get; set; }
       public int age { get; set; }
       public string Address { get; set; }
       public DateTime Birthday { get; set; }

    }
Copy after login

如果不对birthday这个类型处理的话,序列化之后就会出现这个问题:

{"Address":"北京朝阳区","Birthday":"\/Date(1434943392228+0800)\/","Name":"水田如雅","StudentId":"110","age":20}
Copy after login

现在我们在原来的方法上面进行一个改进:

 public static class JsonConvert
    {
        /// <summary>
        /// Converts the obj to json.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t">The t.</param>
        /// <returns>System.String.</returns>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/21 21:40:55</remarks>
        public static string ConvertObjToJson<T>(T t)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(t.GetType());

            try 
	        {	        
		            using (MemoryStream ms=new MemoryStream())
                    {
                        ser.WriteObject(ms,t);
                        string strJson=Encoding.UTF8.GetString(ms.ToArray());
                        //替换Json的date字符串
                        string p = @"\\/Date\((\d+)\+\d+\)\\/";
                        MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDataToDateString);

                        Regex reg = new Regex(p);
                        strJson = reg.Replace(strJson, matchEvaluator);
                        return strJson;
                     }

	        }
	        catch (IOException)
	        {
                //自己处理异常吧
		        return null;
	        }
            
        
        }

        /// <summary>
        /// Jsons the deserialize.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strJson">The STR json.</param>
        /// <returns>``0.</returns>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/21 21:46:37</remarks>
        public static T JsonDeserialize<T>(string strJson)
            where T:class //约束T为class,也可以放宽类型,这里只是个例子,写着玩儿的,欧巴们,此处可改
        {

            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));

            try
            {
                //将"yyyy-MM-dd HH:mm:ss"格式的字符串转为"\/Date(1294499956278+0800)\/"格式

                string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
                MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate);
                Regex reg = new Regex(p);
                strJson = reg.Replace(strJson, matchEvaluator);

                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strJson)))
                {
                    T obj = ser.ReadObject(ms) as T;
                    return obj;
                }
            }
            catch (IOException e)
            {
                //自己处理异常吧
                return null;
            }
           
        }

        /// <summary>
        /// Converts the json data to date string.
        /// </summary>
        /// <param name="m">The m.</param>
        /// <returns>System.String.</returns>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/22 11:39:18</remarks>
        private static string ConvertJsonDataToDateString(Match m) {
            string result = string.Empty;
            DateTime dt = new DateTime(1970, 1, 1);
            dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value));
            dt = dt.ToLocalTime();//转换为本地时间
            result = dt.ToString("yyyy-MM-dd HH:mm:ss");
            return result;
        
        }
        /// <summary>
        /// Converts the date string to json date.
        /// </summary>
        /// <param name="m">The m.</param>
        /// <returns>System.String.</returns>
        /// <remarks>Editor:v-liuhch CreateTime:2015/6/22 11:39:15</remarks>
        private static string ConvertDateStringToJsonDate(Match m) 
        {
            string result = string.Empty;

             DateTime dt = DateTime.Parse(m.Groups[0].Value);

             dt = dt.ToUniversalTime(); 

             TimeSpan ts = dt - DateTime.Parse("1970-01-01");

            result = string.Format("\\/Date({0}+0800)\\/",ts.TotalMilliseconds);

            return result;
        
        }

          
    }
Copy after login

 当然,在序列化的时候,我们可以不对日期时间做单独处理,拿到前台JS之后,再对数据进行一个整合过滤,这样,就不会固定死日期时间的返回格式,感觉这样比在后台处理好。

 以上就是.net——序列化与反序列化中对日期时间的处理的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template