C# - Struggling to Implement a Custom JSON Converter for Polymorphic Types with System.Text.Json
This might be a silly question, but I'm trying to serialize and deserialize a polymorphic object hierarchy using System.Text.Json in .NET 6, but I'm running into issues with type discrimination... I have a base class `Animal` and two derived classes `Dog` and `Cat`. When I try to serialize a list of `Animal` objects, the output is not distinguishing between the types correctly. Hereโs what I have: ```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; } } var animals = new List<Animal> { new Dog { Name = "Rex", Breed = "Labrador" }, new Cat { Name = "Whiskers", IsIndoor = true } }; var options = new JsonSerializerOptions { WriteIndented = true, }; string json = JsonSerializer.Serialize(animals, options); Console.WriteLine(json); ``` The JSON output I get is: ```json [ { "Name": "Rex" }, { "Name": "Whiskers" } ] ``` As you can see, the `Breed` and `IsIndoor` properties are missing from the final output. I tried to create a custom converter for this, but it seems like I don't fully understand how to implement the `JsonConverter<T>` correctly. Here's what I attempted: ```csharp public class AnimalJsonConverter : JsonConverter<Animal> { public override Animal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { // Implementation for deserialization } public override void Write(Utf8JsonWriter writer, Animal value, JsonSerializerOptions options) { // How to differentiate types and write properties accordingly } } ``` I registered the custom converter in my options: ```csharp options.Converters.Add(new AnimalJsonConverter()); ``` But I still canโt seem to get the serialization part working correctly. Can anyone provide guidance on how to properly implement this converter so that all properties of the derived classes are included in the JSON? Also, whatโs the best way to handle the deserialization back to the corresponding types? Any help would be greatly appreciated! Cheers for any assistance!