• JSON.Net 自定义Json序列化时间格式


    JSON.Net 自定义Json序列化时间格式

    Intro

    和 JAVA 项目组对接,他们的接口返回的数据是一个json字符串,里面的时间有的是Unix时间戳,有的是string类型,有的还是空,默认序列化规则没办法反序列化为时间, 所以自定义了一个 Json 时间转换器,支持可空时间类型、string、long(Unix时间戳毫秒)

    Show me the code

    public class CustomDateTimeConverter : JavaScriptDateTimeConverter
        {
            /// <summary>
            /// 重写JavaScriptDateTimeConverter ReadJson 方法
            /// </summary>
            /// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader"/> to read from.</param>
            /// <param name="objectType">Type of the object.</param>
            /// <param name="existingValue">The existing property value of the JSON that is being converted.</param>
            /// <param name="serializer">The calling serializer.</param>
            /// <returns></returns>
            public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
            {
                if (reader.Value == null) //兼容可空时间类型
                {
                    return null;
                }
                else
                {
                    if (reader.TokenType == JsonToken.Date)
                    {
                        return reader.Value;
                    }
                    else if (reader.TokenType == JsonToken.String)
                    {
                        DateTime dt = DateTime.Parse(reader.Value.ToString());
                        return dt;
                    }
                    else
                    {
                        return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(Convert.ToInt64(reader.Value)).ToLocalTime();
                    }
                }
            }
        }

    How To Use

    var model = JsonConvert.DeserializeObject<ResponseModel>(res,new CustomDateTimeConverter());

    End

    如果你有更好的实现方法,欢迎提出

    欢迎随时联系我 weihanli@outlook.com

  • 相关阅读:
    CSUST 4005-你真的会!(分治思维+线段树)
    CSUST 4007-你真的会图论吗?(思维-三元环)
    CSUST 4002-你真的会字符串吗?(DP)
    Odoo下拉动作列表
    Odoo Shell
    Odoo report
    Odoo Web Service API
    Odoo启动过程
    Odoo10 变化
    Odoo10尝鲜:出勤登记
  • 原文地址:https://www.cnblogs.com/weihanli/p/customJsonDatetimeConverter.html
Copyright © 2020-2023  润新知