.net core WebApi: write a custom JsonConverter

.net core 3.0 still cannot handle TimeSpans. So I created my own TimeSpanConverter:

public class TimeSpanConverter : JsonConverter<TimeSpan> {

    public override TimeSpan Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) {
        return TimeSpan.Parse(reader.GetString());
    }

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

Now all it needs is registering in the startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews().AddJsonOptions(options => {
        options.JsonSerializerOptions.Converters.Add(new TimeSpanConverter());
    });
}

Done!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.