简体   繁体   中英

Serialize a generic list with properties of different type of classes

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

you can make your code much more simple if changes your base class

public abstract class Shape
{
    public string Name
    {
        get { return this.GetType().Name; }
    }
}

in this case you can initiate objects more simple and safe way. Also I recommend to use Newtonsoft.Json. It will make your life much easier

var origShapes = new List<Shape>();
    origShapes.Add(new Circle {  Diameter = 2.0 });
    origShapes.Add(new Circle { Diameter = 2.0 });
    origShapes.Add(new Rectangle {  Length = 2.0 });
    origShapes.Add(new Rectangle { Length = 2.0 });

    var json = JsonConvert.SerializeObject(origShapes, Newtonsoft.Json.Formatting.Indented);

result

[
  {
    "Diameter": 2.0,
    "Name": "Circle"
  },
  {
    "Diameter": 2.0,
    "Name": "Circle"
  },
  {
    "Length": 2.0,
    "Name": "Rectangle"
  },
  {
    "Length": 2.0,
    "Name": "Rectangle"
  }
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM