I have a .NET 6 solution for which I'm trying to override the default format of DateTimeOffset
's when calling JsonObject.ToJsonString()
. This is all using the native System.Text.Json
libraries.
I've added a custom DateTimeOffsetConverter
:
public class DateTimeOffsetConverter : JsonConverter<DateTimeOffset>
{
private readonly string _format;
public DateTimeOffsetConverter(string format)
{
_format = format;
}
public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
Debug.Assert(typeToConvert == typeof(DateTimeOffset));
return DateTimeOffset.Parse(reader.GetString());
}
public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString(_format));
}
public override bool CanConvert(Type typeToConvert)
{
return (typeToConvert == typeof(DateTimeOffset));
}
}
But when I try to use it, the code is never hit beyond the constructor being called.
What am I missing that's preventing the JsonConverter
being called?
Here's my code which tries to make use of the functionality:
[Theory]
[InlineData("New Zealand Standard Time")]
[InlineData("India Standard Time")]
[InlineData("Central Brazilian Standard Time")]
[InlineData("W. Australia Standard Time")]
public void DateTimeOffsetIsSerializedCorrectlyTest(string timeZoneId)
{
const string DateTimeFormat = "yyyy-MM-ddTHH:mm:ss.fffzzz";
var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
var dateTimeOffset = new DateTimeOffset(DateTimeOffset.Now.DateTime, timeZoneInfo.BaseUtcOffset);
var json = new JsonObject
{
{ "value", dateTimeOffset }
};
var options = new JsonSerializerOptions
{
Converters = { new DateTimeOffsetConverter(DateTimeFormat) }
};
string jsonString = json.ToJsonString(options);
Assert.Contains(jsonString, dateTimeOffset.ToString(DateTimeFormat));
}
There's a number of closely related question already posted, who's solutions I've experimented with, but none seem to address my precise scenario.