CodexBloom - Programming Q&A Platform

Handling JSON Deserialization with Polymorphic Types in C# - Unexpected Nulls

👀 Views: 10 💬 Answers: 1 📅 Created: 2025-06-08
c# json polymorphism serialization dotnet C#

I'm dealing with I'm stuck trying to Hey everyone, I'm running into an issue that's driving me crazy. I've looked through the documentation and I'm still confused about I'm working on a C# 10 application where I'm trying to deserialize a JSON string into a polymorphic list of objects. The JSON represents different types of animals, and I have a base class `Animal` with derived classes `Dog` and `Cat`. Here’s a simplified version of what my classes look like: ```csharp public class Animal { public string Type { get; set; } } public class Dog : Animal { public string BarkSound { get; set; } } public class Cat : Animal { public string MeowSound { get; set; } } ``` The JSON I'm trying to deserialize looks like this: ```json [ { "Type": "Dog", "BarkSound": "Woof" }, { "Type": "Cat", "MeowSound": "Meow" } ] ``` I'm using `System.Text.Json` to handle the deserialization, and my code looks like this: ```csharp var json = // my JSON string var animals = JsonSerializer.Deserialize<List<Animal>>(json); ``` However, I'm encountering `null` values for the derived properties after deserialization. It seems like the deserializer does not know how to instantiate the derived types based on the `Type` property. I tried to use a custom `JsonConverter`, but I’m not sure how to implement it correctly. Here’s what I attempted: ```csharp public class AnimalConverter : JsonConverter<Animal> { public override Animal Read(ref Utf8JsonReader reader, typeof(Animal), JsonSerializerOptions options) { using (JsonDocument doc = JsonDocument.ParseValue(ref reader)) { var type = doc.RootElement.GetProperty("Type").GetString(); if (type == "Dog") { return JsonSerializer.Deserialize<Dog>(doc.RootElement.GetRawText(), options); } else if (type == "Cat") { return JsonSerializer.Deserialize<Cat>(doc.RootElement.GetRawText(), options); } } throw new JsonException(); } } ``` I registered the converter like this: ```csharp var options = new JsonSerializerOptions(); options.Converters.Add(new AnimalConverter()); var animals = JsonSerializer.Deserialize<List<Animal>>(json, options); ``` Despite this, I still get `null` for `BarkSound` and `MeowSound`. I’m not sure if I’m missing something or if there’s a better way to achieve this. Any ideas or best practices to handle polymorphic deserialization in C# with `System.Text.Json`? How would you solve this? My development environment is Ubuntu. Any ideas what could be causing this? I'm coming from a different tech stack and learning C#. I'd be grateful for any help. This is my first time working with C# latest. Am I approaching this the right way?