Wednesday, June 22, 2022

[.NET 6] Custom Converter for System.Text.Json

Some people asked a question about custom converter for System.Text.Json on Facebook .NET group.
He want user get the specific format from DateTimeOffset (not DateTime)

DateTimeOffset.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fffzzz");
//"2022-06-22 06:28:55.207+00:00"

If using default converter, the result will follow ISO 8601 format

return DateTimeOffset.UtcNow;
//"2022-06-22T05:55:57.4313761+00:00"

And the don't want to use ToString() to achieve it everytime, so the best way is add the custom converter to JsonOptions