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

  

原文地址:https://www.cnblogs.com/fer-team/p/6484086.html