0

I need to serialize an object which has a TimeSpan property, and I need that property to be serialized as "HH:mm:ss". Instead, I get the following:

{"Ticks":561342005619,"Days":0,"Hours":15,"Milliseconds":200,"Minutes":35,"Seconds":34,"TotalDays":0.6497013953923612,"TotalHours":15.592833489416666,"TotalMilliseconds":56134200.5619,"TotalMinutes":935.570009365,"TotalSeconds":56134.2005619}

Is there a way to achieve that?

thyago
  • 31
  • 7
  • https://stackoverflow.com/questions/39876232/newtonsoft-json-serialize-timespan-format – Rezo Megrelidze Feb 01 '22 at 19:02
  • look at Timothy Jannace answer in the link that i've just commented – Rezo Megrelidze Feb 01 '22 at 19:03
  • What version of .net-core are you using? Should be fixed in .net5+ https://dotnetfiddle.net/rKyhPk – haldo Feb 01 '22 at 19:10
  • 1
    Does this answer your question? [.Net Core 3.0 TimeSpan deserialization error - Fixed in .Net 5.0](https://stackoverflow.com/questions/58283761/net-core-3-0-timespan-deserialization-error-fixed-in-net-5-0) – haldo Feb 01 '22 at 19:14
  • @haldo I'm actually using .net5, but it doesn't seem to be fixed. – thyago Feb 02 '22 at 12:12
  • you're right - I just tested in .net-6 and .net-5.0 and it appears to still be broken in .net-5.0.13. Looks like the linked question is incorrect. – haldo Feb 02 '22 at 12:30

1 Answers1

0

You can define your own converter which is described in How to write custom converters for JSON serialization (marshalling) in .NET. You converter could look like this:

public class TimeSpanJsonConverter : JsonConverter<TimeSpan>
{
    public override TimeSpan Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        return TimeSpan.ParseExact(reader.GetString() ?? "", @"hh\:mm\:ss", CultureInfo.InvariantCulture);
    }

    public override void Write(Utf8JsonWriter writer, TimeSpan timeSpanValue, JsonSerializerOptions options)
    {
        writer.WriteStringValue(timeSpanValue.ToString(@"hh\:mm\:ss"));
    }
}

It can then be used for serialization and deserialization:

JsonSerializerOptions serializeOptions = new JsonSerializerOptions
{
    Converters =
    {
        new TimeSpanJsonConverter()
    }
};
string serializedString = JsonSerializer.Serialize(
    objectToSerialize, serializeOptions);
MyObject? deserializedObject = JsonSerializer.Deserialize<MyObject>(
    serializedString, serializeOptions);
Fruchtzwerg
  • 10,999
  • 12
  • 40
  • 49
  • I hopped there was an "out of the box" solution for that. For now, I worked around the problem creating a similar class which has a string instead of the TimeSpan property, so I pass timeSpan.ToString(@"hh\:mm\:ss") to it. I'll try your answer latter. – thyago Feb 02 '22 at 12:20