Parsing ISO Duration with JSON.Net

核能气质少年 提交于 2019-12-17 16:26:42

问题


I have a Web API project with the following settings in 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);

Despite all this, Json.Net cannot parse ISO durations.

It throws this error:

Error converting value "2007-03-01T13:00:00Z/2008-05-11T15:30:00Z" to type 'System.TimeSpan'.

I'm using Json.Net v4.5.

I've tried different values such as "P1M" and others listed on the wiki page with no luck.

So the question is:

  1. Am I missing something?
  2. Or do I have to write some custom formatter?

回答1:


I ran into the same problem and am now using this custom converter to Convert .NET TimeSpans to ISO 8601 Duration strings.

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://stackoverflow.com/questions/12633588/parsing-iso-duration-with-json-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!