Last active
October 20, 2022 20:07
-
-
Save marcominerva/33d405825e06566870f86f00dbc1d9fc to your computer and use it in GitHub Desktop.
TimeOnlyConverter for System.Text.Json in .NET 6.0
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class TimeOnlyConverter : JsonConverter<TimeOnly> | |
{ | |
private readonly string serializationFormat; | |
public TimeOnlyConverter() : this(null) | |
{ | |
} | |
public TimeOnlyConverter(string? serializationFormat) | |
{ | |
this.serializationFormat = serializationFormat ?? "HH:mm:ss.fff"; | |
} | |
public override TimeOnly Read(ref Utf8JsonReader reader, | |
Type typeToConvert, JsonSerializerOptions options) | |
{ | |
var value = reader.GetString(); | |
return TimeOnly.Parse(value!); | |
} | |
public override void Write(Utf8JsonWriter writer, TimeOnly value, | |
JsonSerializerOptions options) | |
=> writer.WriteStringValue(value.ToString(serializationFormat)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for this! This and DateOnlyConverter worked perfectly.