I have the following code
using System;
using System.Collections.Generic;
using System.Text.Json;
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
var shapes = new List<Shape>();
shapes.Add(new Circle { Name = "Circle1", Diameter = 2.0});
shapes.Add(new Circle { Name = "Circle2", Diameter = 2.0});
shapes.Add(new Rectangle { Name = "Rect1", Length = 2.0});
shapes.Add(new Rectangle { Name = "Rect2", Length = 2.0});
var serialized = JsonSerializer.Serialize(shapes);
Console.WriteLine(serialized);
}
public abstract class Shape
{
public string Name { get;set;}
}
public class Circle:Shape
{
public double Diameter { get;set;}
}
public class Rectangle:Shape
{
public double Length {get;set;}
}
}
When serializing, i am losing properties of rectangle and circle, only getting the ones from Shape.
This is the outpout
[{"Name":"Circle1"},{"Name":"Circle2"},{"Name":"Rect1"},{"Name":"Rect2"}]
Which is expected, given that the serializer thinks they are all "Shape", how can i make it so that its smart enough to serialize to proper sub classes