zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    fastapi教程进阶
    fastapi快速入门
    Linux yum安装PostgreSQL9.6
    harbor helm仓库使用
    Dockfile文件解析
    K8S概念理解
    转载---Beats:如何使用Filebeat将MySQL日志发送到Elasticsearch
    Elasticsearch中text与keyword的区别
    filebeat知识点
    logstash知识点
  • 原文地址:https://www.cnblogs.com/weihanli/p/customJsonDatetimeConverter.html
Copyright © 2011-2022 走看看