如何让datetime类型数据接受并且产出long或string类型?

首先引用Newtonsoft.Json.dll,然后,见代码:

View Code
    public class JsonConverterStrAndLongToDate : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(DateTime);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
                                        JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.String)
            {
                return From1970MilinSeconds(Int64.Parse((string)reader.Value));
            }
            else if (reader.TokenType == JsonToken.Integer)
            {
                double s = 5/3;
                return From1970MilinSeconds((Int64)reader.Value);
            }
            throw new JsonReaderException(string.Format("Unexcepted token {0}", reader.TokenType));
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var longValue = (long)(((DateTime)value).AddHours(-8) - new DateTime(1970, 1, 1)).TotalMilliseconds;
            writer.WriteValue(longValue);
        }

        /// <summary>
        /// 将毫秒值转成datetime类型
        /// </summary>
        /// <param name="datetime"></param>
        /// <returns></returns>
        private DateTime From1970MilinSeconds(long datetime)
        {
            datetime *= 10000;

            var ts = new TimeSpan(datetime);
            var dt = new DateTime(1970, 1, 1);
            dt = dt.Add(ts);//距离1970年1月1日的时间
            dt = dt.AddHours(8); 

            return Convert.ToDateTime(dt.ToString());
        }
    }

最后,在序列化时

View Code
 return new ContentResult()
                         {
                             Content = JsonConvert.SerializeObject(result),
                             ContentType = "application/json"
                         };

大功告成!

posted @ 2013-03-21 21:52  瓜王  阅读(403)  评论(0编辑  收藏  举报