.net——序列化与反序列化中对日期时间的处理-阿里云开发者社区

开发者社区> 开发与运维> 正文
登录阅读全文

.net——序列化与反序列化中对日期时间的处理

简介:             承接上篇,现在我在类中加入一个日期时间类型的字段: public class Student { public string StudentId { get; set; } public string Name { get;...



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



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

    }


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


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


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


          

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

          
    }


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


                     









版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

分享: