zoukankan      html  css  js  c++  java
  • 如何让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"
                             };

    大功告成!

  • 相关阅读:
    20200924-2 功能测试
    作业要求20200924-4 代码规范,结对要求
    20200924-1 每周例行报告
    20200929-git地址
    白名单
    作业要求 20200917-1 每周例行报告
    词频统计 SPEC
    20200910-1 每周例行报告
    20200924-3 单元测试,结对
    20200924-5 四则运算试题生成,结对
  • 原文地址:https://www.cnblogs.com/Benjamin/p/2974391.html
Copyright © 2011-2022 走看看