如何使用此格式 "PT0.123875S" 映射 Json 持续时间

How to map a Json duration with this format "PT0.123875S"

我收到一个 json 对象,其字段持续时间与此类似

"duration":"PT0.123875S",

使用 System.Text.Json 什么类型应该接收这个?我应该 TimeSpan 但它不起作用。

好的,System.Text.Json

没有内置转换器

这是一个简单的工作

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

一件重要的事情是这个转换器在很短的时间内是可以的,但是 ISO-8601 不太适合 TimeSpan

Matt Johnson-Pint 在这里解释了原因: 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.