微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/csharp/96081.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐