Skip to content

Support (de)serializing types that implement IDictionary and IDictionary<string, TValue> without hint of implemented type #29870

Description

@layomia

e.g. Given

public class StringToObjectIDictionaryWrapper : IDictionary<string, object>
{
    private readonly IDictionary<string, object> _dict;

    public StringToObjectIDictionaryWrapper(IDictionary<string, object> dict)
    {
        _dict = dict;
    }

    // Implementation for IDictionary<string, object>
    ...
}

After dotnet/corefx#38512 is merged, this will work:

[Fact]
public static void ImplementsIDictionaryOfObject()
{
    var input = new StringToObjectIDictionaryWrapper(new Dictionary<string, object>
    {
        { "Name", "David" },
        { "Age", 32 }
    });

    string json = JsonSerializer.ToString(input, typeof(IDictionary<string, object>)); // Providing implemented type
    Assert.Equal(@"{""Name"":""David"",""Age"":32}", json);

    IDictionary<string, object> obj = JsonSerializer.Parse<IDictionary<string, object>>(json); // Parsing to implemented type
    Assert.Equal(2, obj.Count);
    Assert.Equal("David", ((JsonElement)obj["Name"]).GetString());
    Assert.Equal(32, ((JsonElement)obj["Age"]).GetInt32());
}

This doesn't work

[Fact]
public static void ImplementsIDictionaryOfObject()
{
    var input = new StringToObjectIDictionaryWrapper(new Dictionary<string, object>
    {
        { "Name", "David" },
        { "Age", 32 }
    });

    // This throws NotSupportedException
    string json = JsonSerializer.ToString(input); // Not providing implemented type
    Assert.Equal(@"{""Name"":""David"",""Age"":32}", json);

    // (Assuming json == @"{""Name"":""David"",""Age"":32}") This throws NotSupportedException
    StringToObjectIDictionaryWrapper obj = JsonSerializer.Parse<StringToObjectIDictionaryWrapper>(json); // Parsing to actual type
    Assert.Equal(2, obj.Count);
    Assert.Equal("David", ((JsonElement)obj["Name"]).GetString());
    Assert.Equal(32, ((JsonElement)obj["Age"]).GetInt32());
}

Metadata

Metadata

Assignees

Type

No type

Fields

No fields configured for issues without a type.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions