• 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"  
        }  
    );  
    

      

  • 相关阅读:
    bzoj1731 [Usaco2005 dec]Layout 排队布局
    loj10087 Intervals
    差分约束小结
    bzoj1112 [POI2008]砖块Klo
    bzoj3524 [POI2014]Couriers
    poj2752 Seek the Name, Seek the Fame
    1027C Minimum Value Rectangle
    bzoj2212 [POI2011]Tree Rotations
    bzoj3747 [POI2015]Kinoman
    628D Magic Numbers
  • 原文地址:https://www.cnblogs.com/fer-team/p/6484086.html
Copyright © 2020-2023  润新知