Skip to content

System.Text.Json source generator does not handle reference types with design time custom converter properly #56864

Closed
@DRKV333

Description

@DRKV333

Description

The problem is caused by this part:

// Allow nullable handling to forward to the underlying type's converter.
converter = {JsonMetadataServicesTypeRef}.GetNullableConverter<{typeCompilableName}>(this.{typeFriendlyName});

The source generator always emits this when a JsonConverter attribute is present on the type to serialize, however, the code is only valid for value types.

Here is a minimal setup to reproduce:

public class ReproConverter : JsonConverter<Repro>
{
    public override Repro Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        throw new NotImplementedException();
    }

    public override void Write(Utf8JsonWriter writer, Repro value, JsonSerializerOptions options)
    {
        throw new NotImplementedException();
    }
}

[JsonConverter(typeof(ReproConverter))]
public class Repro
{
}

[JsonSerializable(typeof(Repro))]
public partial class ReproContext : JsonSerializerContext
{
}

The type 'Repro' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'JsonMetadataServices.GetNullableConverter<T>(JsonTypeInfo<T>)'

Configuration

The issue is present on the latest build. (System.Text.Json 6.0.0-rc.1.21404.6)

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions