Skip to content

JsonConverterAttribute should support generic converters on generic types #123208

@eiriktsarpalis

Description

@eiriktsarpalis

The following code:

using System.Text.Json;
using System.Text.Json.Serialization;

JsonSerializer.Serialize(new Option<int>(42));

[JsonConverter(typeof(OptionConverter<>))]
public readonly struct Option<T>
{
    public bool HasValue { get; }
    public T Value { get; }

    public Option(T value)
    {
        HasValue = true;
        Value = value;
    }

    public static implicit operator Option<T>(T value) => new(value);
}

public sealed class OptionConverter<T> : JsonConverter<Option<T>>
{
    public override bool HandleNull => true;

    public override Option<T> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        return new(JsonSerializer.Deserialize<T>(ref reader, options)!);
    }

    public override void Write(Utf8JsonWriter writer, Option<T> value, JsonSerializerOptions options)
    {
        if (!value.HasValue)
        {
            writer.WriteNullValue();
            return;
        }

        JsonSerializer.Serialize(writer, value.Value, options);
    }
}

fails today with the error:

Unhandled exception. System.ArgumentException: Cannot create an instance of OptionConverter`1[T] because Type.ContainsGenericParameters is true.

We should make such use cases work provided that type parameters of the converter precisely match the arity of the targeted type. Such a convention would also work well in the context of the source generator and would provide a good solution for the problem as posited in #73124

Metadata

Metadata

Labels

area-System.Text.JsonenhancementProduct code improvement that does NOT require public API changes/additions

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions