我在 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”和 wiki 页面上列出的其他值,但没有成功。
那么问题是:
- 我是不是漏掉了什么?
- 或者我是否必须编写一些自定义格式化程序?
最佳答案
我遇到了同样的问题,现在正在使用这个自定义转换器将 .NET TimeSpans 转换为 ISO 8601 持续时间字符串。
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?);
}
}
关于c# - 使用 JSON.Net 解析 ISO 持续时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12633588/