c# – 使用JSON.Net解析ISO持续时间

我在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?);
    }
}

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...