Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing ISO Duration with JSON.Net

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?
like image 749
Mrchief Avatar asked Sep 28 '12 04:09

Mrchief


1 Answers

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?);
    }
}
like image 181
Jay Traband Avatar answered Nov 01 '22 03:11

Jay Traband