.NET 6 introduced 2 new types to work with dates and times in .NET. One is the DateOnly
type that represents the Date portion of a DateTime
. The other is the TimeOnly
type that represents the Time portion of a DateTime
.
Unfortunately when you try to use these types inside your data contracts, you get into trouble when you try to Serialize them through the System.Text.Json.JsonSerializer
.
To solve this problem, we can create 2 custom JsonConverter
types:
To use these converters, we need to create and pass an instance of the JsonSerializerOptions where we register these 2 converters:
The generated JSON looks like this:
Hope that helps!