Skip to content

System.Text.Json doesn't deserialize IDictionary with TKey types other than string #44726

@ekvalizer

Description

@ekvalizer

Description

System.Text.Json.Deserialize() cannot deserialize to IDictionary where TKey has type other than string.
I have following example:

       [Test]
        public void DictionaryTest()
        {
            var dic = new Dictionary<int, string>
            {
                {33, "190"},
                {55, "88"}
            };

            var json = JsonSerializer.Serialize(dic);

            var deserialized = JsonSerializer.Deserialize<IDictionary<int, string>>(json);
            Assert.IsNotNull(deserialized);
        }

This code above would throw exception System.InvalidCastException : Unable to cast object of type 'System.Collections.Generic.Dictionary2[System.String,System.String]' to type 'System.Collections.Generic.IDictionary2[System.Int32,System.String]'.

However if i only change IDictinary type to Dictionary it will work. It seems strange for me because similar example for ICollection<int> would work and i'll get List object.

Configuration

.net 5.0.100
Windows 10 18363.1198 (x64)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions