DateOnly and TimeOnly types for .NET versions before 6.0
$ dotnet add package Portable.System.DateTimeOnly.Json
Portable.System.DateTimeOnly.JsonThe System.Text.Json NuGet package contains the built-in support for the System.DateOnly and System.TimeOnly types serialization/deserialization. Of course, the backported versions of the same types from the Portable.System.DateTimeOnly NuGet package are not supported by default by this library. If you already use the portable versions of these types in your code and want to make them compatible with the System.Text.Json you can implement custom converters or use this package for cross-framework compatible approach.
The package provides two concrete implementations of the System.Text.Json.Serialization.JsonConverter<T> class: System.Text.Json.DateOnlyConverter and System.Text.Json.TimeOnlyConverter for converting System.DateOnly and System.TimeOnly data types. You can use this converter as usual System.Text.Json converters: with the System.Text.Json.Serialization.JsonConverterAttribute attribute or System.Text.Json.JsonSerializerOptions.Converters property.
The main disadvantage of this "direct" approach for configuring System.DateOnly and System.TimeOnly data types handling by the System.Text.Json library is that in this case you'll always use the backported converters even if your code runs on .NET 6 and later. The package also provides two helper attributes System.Text.Json.DateOnlyConverterAttribute and System.Text.Json.TimeOnlyConverterAttribute for mitigating this problem. These attributes use built-in converters on .NET 6 and later and fall back to the backported one in other cases.
Unfortunately, attributes-based approach will not work if you'll try to use System.DateOnly and/or System.TimeOnly data types with the System.Text.Json source generators. The only way to make generated code compilable is to use any type names not equal to System.DateOnly and/or System.TimeOnly available in object graph processed by the source generator.
The package provides two helper types: System.Text.Json.JsonDateOnly and System.Text.Json.JsonTimeOnly to solve this problem. These types have no public properties, but they provide implicit conversion operations from/to the System.DateOnly and System.TimeOnly data types respectively. You can use them safely in your JSON-mapping objects with any kind of serialization available in the System.Text.Json library. These types have custom System.Text.Json.Serialization.JsonConverterAttribute applied with helper converters that delegate work to System.Text.Json.DateOnlyConverter and System.Text.Json.TimeOnlyConverter types without code duplication.
Thanks a lot for all contributors. See the full list of project supporters in the CONTRIBUTORS file.
This project uses PVS-Studio - static analyzer for C, C++, C#, and Java code.