Last active
October 20, 2022 20:07
-
-
Save marcominerva/8640e9d2e556fc78e3f3d079a207c778 to your computer and use it in GitHub Desktop.
DateOnlyConverter 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 DateOnlyConverter : JsonConverter<DateOnly> | |
{ | |
private readonly string serializationFormat; | |
public DateOnlyConverter() : this(null) | |
{ | |
} | |
public DateOnlyConverter(string? serializationFormat) | |
{ | |
this.serializationFormat = serializationFormat ?? "yyyy-MM-dd"; | |
} | |
public override DateOnly Read(ref Utf8JsonReader reader, | |
Type typeToConvert, JsonSerializerOptions options) | |
{ | |
var value = reader.GetString(); | |
return DateOnly.Parse(value!); | |
} | |
public override void Write(Utf8JsonWriter writer, DateOnly 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