0

I'm receiving a json object with a field duration like this

"duration":"PT0.123875S",

With System.Text.Json what type is supposed to receive this ? I was expected TimeSpan but it does not work.

JuChom
  • 5,717
  • 5
  • 45
  • 78

1 Answers1

0

Ok, there is no built in converter for System.Text.Json

Here is a simple one doing the job

public class Iso8601DurationConverter : JsonConverter<TimeSpan>
{
    public override TimeSpan Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options)
    {
        return XmlConvert.ToTimeSpan(reader.GetString());
    }

    public override void Write(Utf8JsonWriter writer, TimeSpan value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(XmlConvert.ToString(value));
    }
}

One important thing is that for very short duration this converter is ok, but ISO-8601 does not fit very well with TimeSpan

Matt Johnson-Pint explains why here : https://github.com/dotnet/runtime/issues/29932#issuecomment-856137910

The issue with using the ISO860 period format is that it can represent values that don't fit cleanly into a TimeSpan. So if one had in their JSON something like "P3M" (3 months), the best one could do for a TimeSpan would be to use an average month duration, such as 3 months of 30 days each of exactly 24 hours long. Of course, such values wouldn't survive a round trip either, because it could come out as "P90D" or "P2160H", or a variety of other ways.

JuChom
  • 5,717
  • 5
  • 45
  • 78