>  기사  >  백엔드 개발  >  .net - 직렬화 및 역직렬화에서 날짜 및 시간 처리

.net - 직렬화 및 역직렬화에서 날짜 및 시간 처리

黄舟
黄舟원래의
2017-02-24 10:35:441597검색

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

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之后,再对数据进行一个整合过滤,这样,就不会固定死日期时间的返回格式,感觉这样比在后台处理好。

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


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.