How to resolve the generic form of a JsonConverter in System.Text.Json

  Kiến thức lập trình

I know that this issue is more a question of the limitations of C# generics than it is a question about .NET Core (8.0) JSON Serialization but it is driving me crazy.

When getting ‘underneath the hood’ of System.Text.Json, for example, when writing Custom Converters, the accepted way to retrieve a ‘registered’ JsonConverter is to call options.GetConverter(…) passing the type to convert.

The method returns the non-generic JsonConverter type even though all converters are generic, i.e. of type JsonConverter. The non-generic type cannot be used for serialization/deserialization because it doesn’t have the required Read/Write methods.

This has led me to ‘throwing the baby out with the bath water’ and abandoning the built-in converter registry and JsonSerializerOption.GetConverter(…) in favour of a Dictionary which maps types to type-specific ‘serializer’ or ‘deserializer’ Delegates which perform the necessary Read/Write operations.

These can be written so as to use the existing converter registry as follows:

This is a pain, but relatively organized and easy to do.

That said, it seems like overkill.

So my question, or questions, is/are:

  1. Is there a better solution to this old chestnut?

  2. Is it really impossible in generic typing to resolve a non-generic base type to its generic equivalent even when this is the implemented form without declaring the type explicitly as in the above (i.e. using a Type rather than ), or is C# generics being over-restrictive here?

private delegate void Serializer(Utf8JsonWriter writer, object? value, JsonSerializerOptions options);

private static readonly Dictionary<Type, Serializer> _Serializers = new Dictionary<Type, Serializer>
    { typeof(string), SerializeStringValue }

private static void SerializeStringValue(Utf8JsonWriter writer, object? value, JsonSerializerOptions options)
    var converter = options.GetConverter(typeof(string));
    if (value is string stringValue && converter is JsonConverter<string> stringConverter)
        stringConverter.Write(writer, stringValue, options);

New contributor

Exertive Studio is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website