C# 10 - implementing Serialization of Dictionary with Custom Key Type in System.Text.Json
I'm wondering if anyone has experience with I've been banging my head against this for hours. I'm having trouble serializing a dictionary that uses a custom class as the key in C# 10 with the System.Text.Json library. My class, `CustomKey`, overrides `GetHashCode` and `Equals`, but when I try to serialize a dictionary with this key type, I get a `JsonException` stating that it want to convert the value of type 'CustomKey' to a JSON value. Here's the relevant code: ```csharp public class CustomKey { public string Id { get; set; } public override int GetHashCode() => Id.GetHashCode(); public override bool Equals(object obj) => obj is CustomKey key && Id == key.Id; } public class Example { public Dictionary<CustomKey, string> MyDictionary { get; set; } = new(); } var example = new Example(); example.MyDictionary[new CustomKey { Id = "1" }] = "First"; var json = JsonSerializer.Serialize(example); ``` I've tried implementing `JsonConverter<CustomKey>` to handle the custom serialization, but it doesn't seem to be invoked. Here's what I attempted: ```csharp public class CustomKeyConverter : JsonConverter<CustomKey> { public override CustomKey Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { reader.Read(); // Move to string return new CustomKey { Id = reader.GetString() }; } public override void Write(Utf8JsonWriter writer, CustomKey value, JsonSerializerOptions options) { writer.WriteStringValue(value.Id); } } var options = new JsonSerializerOptions(); options.Converters.Add(new CustomKeyConverter()); var json = JsonSerializer.Serialize(example, options); ``` However, I still receive the same exception. Is there something I'm missing with the `JsonConverter`? Should I be implementing the converter differently, or is there an scenario with how I'm setting it up? Any help would be greatly appreciated! This is part of a larger API I'm building. Thanks in advance! This issue appeared after updating to C# stable. Any ideas what could be causing this? Any examples would be super helpful.