Skip to content

System.Text.Json source generator not handling converter factories correctly #58267

Closed

Description

@eiriktsarpalis

The code

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

JsonSerializer.Serialize(new MyClass(), MyJsonContext.Default.MyClass);

[JsonSerializable(typeof(MyClass))]
public partial class MyJsonContext : JsonSerializerContext
{
}

public class MyClass
{
    public MyEnum Value { get; set; }
}

[JsonConverter(typeof(JsonStringEnumConverter))]
public enum MyEnum
{
    X = 0
}

Fails with an InvalidOperationException. This is because the the generated JsonTypeInfo<MyEnum> constructor is attempting to pass the custom converter without checking if it's a factory.

Generated code

// <auto-generated/>
#nullable enable
    public partial class MyJsonContext
    {
        private global::System.Text.Json.Serialization.Metadata.JsonTypeInfo<global::MyEnum>? _MyEnum;
        public global::System.Text.Json.Serialization.Metadata.JsonTypeInfo<global::MyEnum> MyEnum
        {
            get
            {
                if (_MyEnum == null)
                {
                    global::System.Text.Json.Serialization.JsonConverter? customConverter;
                        if (Options.Converters.Count > 0 && (customConverter = GetRuntimeProvidedCustomConverter(typeof(global::MyEnum))) != null)
                        {
                            _MyEnum = global::System.Text.Json.Serialization.Metadata.JsonMetadataServices.CreateValueInfo<global::MyEnum>(Options, customConverter);
                        }
                        else
                        {
                            global::System.Text.Json.Serialization.JsonConverter converter = new global::System.Text.Json.Serialization.JsonStringEnumConverter();
                                global::System.Type typeToConvert = typeof(global::MyEnum);
                                if (!converter.CanConvert(typeToConvert))
                                {
                                    global::System.Type? underlyingType = global::System.Nullable.GetUnderlyingType(typeToConvert);
                                    if (underlyingType != null && converter.CanConvert(underlyingType))
                                    {
                                        global::System.Text.Json.Serialization.JsonConverter? actualConverter = converter;
            
                                        if (converter is global::System.Text.Json.Serialization.JsonConverterFactory converterFactory)
                                        {
                                            actualConverter = converterFactory.CreateConverter(underlyingType, Options);
            
                                            if (actualConverter == null || actualConverter is global::System.Text.Json.Serialization.JsonConverterFactory)
                                            {
                                                throw new global::System.InvalidOperationException($"JsonConverterFactory '{converter} cannot return a 'null' or 'JsonConverterFactory' value.");
                                            }
                                        }
            
                                        // Allow nullable handling to forward to the underlying type's converter.
                                        converter = global::System.Text.Json.Serialization.Metadata.JsonMetadataServices.GetNullableConverter<global::MyEnum>(this.MyEnum);
                                    }
                                    else
                                    {
                                        throw new global::System.InvalidOperationException($"The converter '{converter.GetType()}' is not compatible with the type '{typeToConvert}'.");
                                    }
                                }
            
                                _MyEnum = global::System.Text.Json.Serialization.Metadata.JsonMetadataServices.CreateValueInfo<global::MyEnum>(Options, converter);
                        }
                }
        
                return _MyEnum;
            }
        }
    }

Activity

  1. added this to the 6.0.0 milestone on Aug 27, 2021
  2. ghost added
    untriaged
    on Aug 27, 2021
  3. eiriktsarpalis commented on Aug 27, 2021

    @eiriktsarpalis
    MemberAuthor

    Related to #58119 and #56864.

  4. eiriktsarpalis commented on Aug 27, 2021

    @eiriktsarpalis
    MemberAuthor

    Similarly when attaching the attribute on the property level

    using System.Text.Json;
    using System.Text.Json.Serialization;
    
    System.Console.WriteLine(JsonSerializer.Serialize(new MyClass(), MyJsonContext.Default.MyClass));
    
    [JsonSerializable(typeof(MyClass))]
    public partial class MyJsonContext : JsonSerializerContext
    {
    }
    
    public class MyClass
    {
        [JsonConverter(typeof(JsonStringEnumConverter))]
        public MyEnum Value { get; set; }
    }
    
    public enum MyEnum
    {
        X = 0
    }

    I'm getting a compiler error:

    1>C:\Users\eitsarpa\source\repos\ConsoleApp1\ConsoleApp1\System.Text.Json.SourceGeneration\System.Text.Json.SourceGeneration.JsonSourceGenerator\MyJsonContext.MyClass.g.cs(51,28,51,96): error CS1503: Argument 7: cannot convert from 'System.Text.Json.Serialization.JsonStringEnumConverter' to 'System.Text.Json.Serialization.JsonConverter<MyEnum>?'
    

    from the generated code

    properties[0] = global::System.Text.Json.Serialization.Metadata.JsonMetadataServices.CreatePropertyInfo<global::MyEnum>(
        options,
        isProperty: true,
        isPublic: true,
        isVirtual: false,
        declaringType: typeof(global::MyClass),
        propertyTypeInfo: jsonContext.MyEnum,
        converter: new global::System.Text.Json.Serialization.JsonStringEnumConverter(),
        getter: static (obj) => ((global::MyClass)obj).Value,
        setter: static (obj, value) => ((global::MyClass)obj).Value = value!,
        ignoreCondition: null,
        hasJsonInclude: false,
        numberHandling: default,
        propertyName: "Value",
        jsonPropertyName: null);

    Again, this happens because we're trying to cast the converter factory to JsonConverter<MyEnum>.

  5. removed
    untriaged
    on Aug 27, 2021
  6. self-assigned this
    on Aug 27, 2021
  7. added
    in-pr
    on Aug 30, 2021
  8. layomia commented on Sep 8, 2021

    @layomia
    Contributor

    Fixed for 6.0 in #58652 cc @steveharter, @eiriktsarpalis.

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

Metadata

Metadata

Assignees

Labels

area-System.Text.Jsonblocking-releasebugin-pr

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions