CodexBloom - Programming Q&A Platform

Unexpected Serialization implementing System.Text.Json in .NET 7 When Using Polymorphism

👀 Views: 76 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
json serialization dotnet polymorphism system.text.json C#

This might be a silly question, but I'm working with a question with serialization using `System.Text.Json` in .NET 7 when I try to serialize an object that employs polymorphism. I have a base class `Animal` and a derived class `Dog`. When I attempt to serialize a list of `Animal` that contains instances of `Dog`, I end up with the following behavior: ``` System.Text.Json.JsonException: Unable to serialize the polymorphic type 'Namespace.Dog'. ``` I've implemented a custom converter to handle this type of scenario: ```csharp public class AnimalJsonConverter : JsonConverter<Animal> { public override Animal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { // Implementation to deserialize } public override void Write(Utf8JsonWriter writer, Animal value, JsonSerializerOptions options) { JsonSerializer.Serialize(writer, value, value.GetType(), options); } } ``` I register the converter like this: ```csharp var options = new JsonSerializerOptions { Converters = { new AnimalJsonConverter() } }; var animals = new List<Animal> { new Dog() }; var json = JsonSerializer.Serialize(animals, options); ``` Despite having the converter, I'm still getting the serialization exception. I've tried adding `[JsonConverter(typeof(AnimalJsonConverter))]` to the base class but that didn't seem to help. I also verified that my `Dog` class is not marked as abstract and has a parameterless constructor. Any insights on what could be causing this scenario or how I can resolve it? I'm currently using .NET 7.0.100 and this question only seems to occur when the list is being serialized directly without any specific type being defined. I'm working on a API that needs to handle this. Am I missing something obvious?