C# - Exception when using custom JsonConverter for polymorphic types in System.Text.Json
This might be a silly question, but I'm trying to figure out I'm writing unit tests and I tried several approaches but none seem to work..... I'm currently facing an issue when trying to deserialize polymorphic types using a custom `JsonConverter` with `System.Text.Json` in .NET 5. I have a base class `Animal` and derived classes `Dog` and `Cat`. My `JsonConverter` is intended to read the type from the JSON and instantiate the appropriate subclass, but I'm encountering a `JsonException` with the message: "Cannot convert JSON to type 'Namespace.Animal'". Hereโs the relevant code for my converter: ```csharp public class AnimalConverter : JsonConverter<Animal> { public override Animal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { using (JsonDocument doc = JsonDocument.ParseValue(ref reader)) { var root = doc.RootElement; string type = root.GetProperty("type").GetString(); return type switch { "dog" => JsonSerializer.Deserialize<Dog>(root.GetRawText(), options), "cat" => JsonSerializer.Deserialize<Cat>(root.GetRawText(), options), _ => throw new JsonException("Unknown animal type") }; } } public override void Write(Utf8JsonWriter writer, Animal value, JsonSerializerOptions options) { throw new NotImplementedException(); } } ``` I registered this converter in my `JsonSerializerOptions`: ```csharp var options = new JsonSerializerOptions(); options.Converters.Add(new AnimalConverter()); ``` And hereโs the JSON Iโm trying to deserialize: ```json { "type": "dog", "name": "Buddy" } ``` When I run the deserialization like this: ```csharp var animal = JsonSerializer.Deserialize<Animal>(jsonString, options); ``` I get the mentioned `JsonException`. Iโve confirmed that the JSON is valid and matches the expected structure. Am I missing something in the deserialization process, or is there a more appropriate way to handle polymorphic deserialization with `System.Text.Json`? Any insights or suggestions would be greatly appreciated! This is part of a larger web app I'm building. I'd really appreciate any guidance on this. Any help would be greatly appreciated! Is there a better approach? Thanks for your help in advance!