我有一个 Web API 项目,其中包含以下设置Global.asax.cs
:
var serializerSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc
};
serializerSettings.Converters.Add(new IsoDateTimeConverter());
var jsonFormatter = new JsonMediaTypeFormatter { SerializerSettings = serializerSettings };
jsonFormatter.MediaTypeMappings.Add(GlobalConfiguration.Configuration.Formatters[0].MediaTypeMappings[0]);
GlobalConfiguration.Configuration.Formatters[0] = jsonFormatter;
WebApiConfig.Register(GlobalConfiguration.Configuration);
尽管如此,Json.Net 无法解析ISO 持续时间。
它抛出这个错误:
将值“2007-03-01T13:00:00Z/2008-05-11T15:30:00Z”转换为类型“System.TimeSpan”时出错。
我正在使用 Json.Net v4.5。
我尝试了不同的值,例如“P1M”和wiki页面上列出的其他值,但没有成功。
所以问题是:
- 我错过了什么吗?
- 还是我必须编写一些自定义格式化程序?