Skip to content

Types deriving from concrete collection types aren't supported by JsonSerializer #29981

Description

@pranavkm

Consider:

    class Program
    {
        static void Main(string[] args)
        {
            var dictionary= new MyDictionary
            {
                { "Hello", "World" },
            };

            var x = JsonSerializer.ToString(dictionary);
            System.Console.WriteLine(x);
        }
    }

    public class MyDictionary : Dictionary<string, object>
    {
    }

This fails to serialize with the following error:

Unhandled exception. System.NotSupportedException: The collection type 'dictionary.MyDictionary' is not supported.
   at System.Text.Json.JsonClassInfo.GetElementType(Type propertyType, Type parentType, MemberInfo memberInfo, JsonSerializerOptions options)
   at System.Text.Json.JsonClassInfo.CreateProperty(Type declaredPropertyType, Type runtimePropertyType, PropertyInfo propertyInfo, Type parentClassType, JsonSerializerOptions options)
   at System.Text.Json.JsonClassInfo.AddProperty(Type propertyType, PropertyInfo propertyInfo, Type classType, JsonSerializerOptions options)
   at System.Text.Json.JsonClassInfo..ctor(Type type, JsonSerializerOptions options)

Similarly, this does not work either:

class Program
{
    static void Main(string[] args)
    {
        var list = new MyList { "A", "B" };
        var json = JsonSerializer.ToString(list);
        System.Console.WriteLine(json);
    }
}

public class MyList : List<string>
{
}

Haven't tried out other collection types, happened to run in to these two. For the first case, there is an actual MVC scenario for this: https://github.com/aspnet/AspNetCore/blob/master/src/Mvc/Mvc.Core/src/SerializableError.cs. If it happens to be fairly trivial to fix this, we'd love to see this fixed.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions