我在Global.asax.cs中有一个具有以下设置的Web API项目:
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 durations.
它会抛出这个错误:
Error converting value “2007-03-01T13:00:00Z/2008-05-11T15:30:00Z” to
type ‘System.TimeSpan’.
我使用Json.Net v4.5.
我尝试过不同的值,如“P1M”和维基页面上列出的其他值,没有运气.
所以问题是:
我错过了什么吗?
>还是要写一些自定义格式化程序?
解决方法
我遇到同样的问题,现在使用这个自定义转换器将.NET TimeSpans转换为ISO 8601 Duration字符串.
public class TimeSpanConverter : JsonConverter { public override void WriteJson(JsonWriter writer,object value,JsonSerializer serializer) { var ts = (TimeSpan) value; var tsString = XmlConvert.ToString(ts); serializer.Serialize(writer,tsString); } public override object ReadJson(JsonReader reader,Type objectType,object existingValue,JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { return null; } var value = serializer.Deserialize<String>(reader); return XmlConvert.ToTimeSpan(value); } public override bool CanConvert(Type objectType) { return objectType == typeof (TimeSpan) || objectType == typeof (TimeSpan?); } }