欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-10-16 11:26:43
    承接上篇,现在我在类中加入一个日期时间类型的字段:       public class Student...

 

 

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

 

 

 

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
    {
        /// 
        /// Converts the obj to json.
        /// 
        /// 
        ///The t.
        /// System.String.
        /// Editor:v-liuhch CreateTime:2015/6/21 21:40:55
        public static string ConvertObjToJson(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;
	        }
            
        
        }

        /// 
        /// Jsons the deserialize.
        /// 
        /// 
        ///The STR json.
        /// ``0.
        /// Editor:v-liuhch CreateTime:2015/6/21 21:46:37
        public static T JsonDeserialize(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;
            }
           
        }

        /// 
        /// Converts the json data to date string.
        /// 
        ///The m.
        /// System.String.
        /// Editor:v-liuhch CreateTime:2015/6/22 11:39:18
        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;
        
        }
        /// 
        /// Converts the date string to json date.
        /// 
        ///The m.
        /// System.String.
        /// Editor:v-liuhch CreateTime:2015/6/22 11:39:15
        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之后,再对数据进行一个整合过滤,这样,就不会固定死日期时间的返回格式,感觉这样比在后台处理好。