Deserializing IReadOnlyDictionary with integer key throws InvalidCastException
System.Text.Json 5.0.0 supports dictionaries with integer keys:
{
"1": "foo"
}
This can be deserialized to a dictionary (not read-only) with int keys:
var dictionary = JsonSerializer.Deserialize<Dictionary<int, string>>(json);
There is also support for IReadOnlyDictionary<TKey, TValue> when TKey is string:
var dictionary = JsonSerializer.Deserialize<IReadOnlyDictionary<string, string>>(json);
However, when I try to deseriailze IReadOnlyDictionary<TKey, TValue> when TKey is int I get an InvalidCastException:
Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.String]' to type 'System.Collections.Generic.Dictionary`2[System.Int32,System.String]'. at System.Text.Json.Serialization.Converters.IReadOnlyDictionaryOfTKeyTValueConverter`3.Add(TKey key, TValue& value, JsonSerializerOptions options, ReadStack& state) at System.Text.Json.Serialization.Converters.DictionaryDefaultConverter`3.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, TCollection& value) at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value) at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state) at System.Text.Json.JsonSerializer.ReadCore[TValue](JsonConverter jsonConverter, Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state) at System.Text.Json.JsonSerializer.ReadCore[TValue](Utf8JsonReader& reader, Type returnType, JsonSerializerOptions options) at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, Type returnType, JsonSerializerOptions options) at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options)
I find it surprising the both dictionaries with int keys and IReadOnlyDictionary are supported but not when you combine them. If there is no intention to support the combination then a better exception type should be used to signal that instead of InvalidCastException.
Deserializing IDictionary<TKey, TValue> with int key suffers from the same problem.
Duplicate of https://github.com/dotnet/runtime/issues/44726. A servicing fix for 5.0.2 is planned - see: https://github.com/dotnet/runtime/pull/45449.