Skip to content

STJ source generator does not correctly wrap custom converters on nullable properties #81833

Closed

Description

@eiriktsarpalis

Consider the following code:

var value = new MyPoco { Value = MyEnum.A };

Console.WriteLine(JsonSerializer.Serialize(value)); // works as expected
Console.WriteLine(JsonSerializer.Serialize(value, MyContext.Default.MyPoco));
// System.ArgumentException: GenericArguments[0], 'System.Nullable`1[MyEnum]', on 'System.Text.Json.Serialization.Converters.EnumConverter`1[T]' violates the constraint of type 'T'.
//   at System.RuntimeTypeHandle.Instantiate(RuntimeType inst)
//   at System.RuntimeType.MakeGenericType(Type[] instantiation)
//   -- - End of inner exception stack trace ---
//   at System.RuntimeType.ValidateGenericArguments(MemberInfo definition, RuntimeType[] genericArguments, Exception e)
//   at System.RuntimeType.MakeGenericType(Type[] instantiation)
//   at System.Text.Json.Serialization.Converters.EnumConverterFactory.Create(Type enumType, EnumConverterOptions converterOptions, JsonNamingPolicy namingPolicy, JsonSerializerOptions options)
//   at MyContext.GetConverterFromFactory(JsonSerializerOptions options, Type type, JsonConverterFactory factory) in C: \Users\eitsarpa\source\repos\ConsoleApp1\ConsoleApp1\System.Text.Json.SourceGeneration\System.Text.Json.SourceGeneration.JsonSourceGenerator\MyContext.g.cs:line 77
//   at MyContext.GetConverterFromFactory[T] (JsonSerializerOptions options, JsonConverterFactory factory) in C: \Users\eitsarpa\source\repos\ConsoleApp1\ConsoleApp1\System.Text.Json.SourceGeneration\System.Text.Json.SourceGeneration.JsonSourceGenerator\MyContext.g.cs:line 72

public class MyPoco
{
    [JsonConverter(typeof(JsonStringEnumConverter))]
    public MyEnum? Value { get; set; }
}

public enum MyEnum { A, B, C };

[JsonSerializable(typeof(MyPoco))]
public partial class MyContext : JsonSerializerContext
{ }

By convention, the reflection serializer automatically wraps custom property converters on nullable types. We should update the source generator to do the same.

Activity

  1. ghost added
    untriaged
    on Feb 8, 2023
  2. added
    source-generator
    and removed
    untriaged
    on Feb 8, 2023
  3. added this to the Future milestone on Feb 8, 2023
  4. eiriktsarpalis commented on Feb 9, 2023

    @eiriktsarpalis
    MemberAuthor

    Should be addressed in conjunction with #79311

  5. eiriktsarpalis commented on Jun 7, 2023

    @eiriktsarpalis
    MemberAuthor

    Fixed in #84208

  6. ghost locked as resolved and limited conversation to collaborators on Jul 8, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Text.Jsonbugsource-generator

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions