zoukankan      html  css  js  c++  java
  • WebAPI序列化后的时间中含有“T”的解决方法

    问题:

      {  
        "name": "abc",  
        "time": "2015-02-10T15:18:21.7046433+08:00"  
    }
    

      

    解决方法:

    1、在WebApiConfig.cs的Register方法中加入以下语句,插入自定义的JsonDateTimeConverter格式

    GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Insert(  
                    0, new JsonDateTimeConverter());  
    

    2、新建一个类,名为JsonDateTimeConverter.cs,重写IsoDateTimeConverter的ReadJson方法,内容如下

    /// <summary>  
    /// Json日期带T格式转换  
    /// </summary>  
    public class JsonDateTimeConverter : IsoDateTimeConverter  
    {  
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)  
        {  
            DateTime dataTime;  
            if (DateTime.TryParse(reader.Value.ToString(), out dataTime))  
            {  
                return dataTime;  
            }  
            else  
            {  
                return existingValue;  
            }  
        }  
      
        public JsonDateTimeConverter()  
        {  
            DateTimeFormat = "yyyy-MM-dd HH:mm:ss";  
        }  
    }  
    

      在web api中,我们可以在WebApiConfig.cs的Register函数中新增以下配置来定义返回的时间类型格式

    //配置返回的时间类型数据格式  
    GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(  
        new Newtonsoft.Json.Converters.IsoDateTimeConverter()  
        {  
            DateTimeFormat = "yyyy-MM-dd hh:mm:ss"  
        }  
    );  
    

      

  • 相关阅读:
    几个ID
    一百层高楼和两个棋子
    快速了解的链接 shell sed awk
    用shell实现一个“输入密码”程序
    i love you do you love me
    打造全新视觉环境
    【转】LINUX 环境变量总结
    TextBox输入限制
    获取CPU和硬盘序列号
    Lable属性设置(winform)
  • 原文地址:https://www.cnblogs.com/fer-team/p/6484086.html
Copyright © 2011-2022 走看看