Skip to content

JsonConverter doesn't allow injection of parameters #42975

@fbrum

Description

@fbrum

I wanted to create a converter for DateTimeOffset and having the date format being injected from configuration.
But I came to conclude that is not possible. I created a base converter

public abstract class ConvertNullableDateTime : JsonConverter<DateTimeOffset?>
{
     protected abstract string Format { get; }
     protected abstract TimeSpan Offset { get; }

     public override DateTimeOffset? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
     {
         return DateTime.Parse(reader.GetString());
     }
     public override void Write(Utf8JsonWriter writer, DateTimeOffset? value, JsonSerializerOptions options)
     {
         writer.WriteStringValue(value?.ToOffset(Offset).ToString(Format));
     }
}

And then I defined a specific converter:

public class ToNullableDateTimeOffset : ConvertNullableDateTime
{
    public ToNullableDateTimeOffset()
    {
        Format = String.Empty;
        Offset = new TimeSpan();
    }

    public ToNullableDateTimeOffset(string dateTimeFormat, TimeSpan offset)
    {
        Format = dateTimeFormat;
        Offset = offset;
    }

    protected override string Format { get; }
    protected override TimeSpan Offset { get; }
}

Added the serializer with the converter to the collection:

self.AddSingleton<ISerializer>( provider => 
{
    var timeSpan = new TimeSpan(clientOptions.Offset);
    SerializerSettings.Converters.Add(new ToNullableDateTimeOffset(clientOptions.DateTimeFormat!, timeSpan));

    return new JsonNetSerializer(provider.GetService<ILogger<JsonNetSerializer>>(), SerializerSettings);
});

I had to create a empty constructor because otherwise I would have a NullException while serializing.
And the constructor with the injected properties are not used. on the serialization.

I searched arround but was not able to find anything solution.
Could this be done for a future version?
Thanks

PS. Sorry but I'm not able to get the code formated correctly

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Text.Jsonneeds-author-actionAn issue or pull request that requires more info or actions from the author.questionAnswer questions and provide assistance, not an issue with source code or documentation.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions