CodexBloom - Programming Q&A Platform

How to Handle JSON Deserialization implementing Polymorphic Types in .NET 6 using System.Text.Json?

๐Ÿ‘€ Views: 410 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-11
c# .net-6 json serialization polymorphism C#

I'm dealing with I've searched everywhere and can't find a clear answer... I'm working with a scenario with JSON deserialization in .NET 6 using the `System.Text.Json` library when working with polymorphic types. My scenario involves a base class `Animal` and derived classes `Dog` and `Cat`. The JSON being deserialized has a type discriminator field, but I keep getting an `InvalidOperationException` stating that the converter want to handle the provided type. Hereโ€™s my base structure: ```csharp public abstract class Animal { public string Name { get; set; } } public class Dog : Animal { public string Breed { get; set; } } public class Cat : Animal { public bool IsIndoor { get; set; } } ``` The JSON looks something like this: ```json [ { "Type": "Dog", "Name": "Rex", "Breed": "Labrador" }, { "Type": "Cat", "Name": "Whiskers", "IsIndoor": true } ] ``` Iโ€™ve tried creating a custom converter for `Animal`, but it seems to be bypassed. Hereโ€™s the converter I attempted: ```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 jsonObject = doc.RootElement; string type = jsonObject.GetProperty("Type").GetString(); if (type == "Dog") return JsonSerializer.Deserialize<Dog>(jsonObject.GetRawText(), options); else if (type == "Cat") return JsonSerializer.Deserialize<Cat>(jsonObject.GetRawText(), options); } throw new JsonException(); } public override void Write(Utf8JsonWriter writer, Animal value, JsonSerializerOptions options) { JsonSerializer.Serialize(writer, value, value.GetType(), options); } } ``` And I registered the converter like this: ```csharp var options = new JsonSerializerOptions(); options.Converters.Add(new AnimalConverter()); ``` However, when I try to deserialize using: ```csharp var animals = JsonSerializer.Deserialize<List<Animal>>(jsonString, options); ``` I get the behavior `InvalidOperationException: want to convert JSON to target type 'System.Type'`. It seems like the deserializer want to determine the type due to the way Iโ€™m trying to handle it. Iโ€™ve also verified that the JSON string is correctly formatted. Any guidance on how to correctly set up polymorphic deserialization with `System.Text.Json` would be greatly appreciated! This is part of a larger CLI tool I'm building. Thanks in advance! The stack includes C# and several other technologies.