【问题标题】:Serialize a generic list with properties of different type of classes序列化具有不同类型类属性的通用列表
【发布时间】:2022-01-30 05:46:13
【问题描述】:

我有以下代码

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;}
    }   
    
}

序列化时,我丢失了矩形和圆形的属性,只从 Shape 中获取。

这是输出

[{"Name":"Circle1"},{"Name":"Circle2"},{"Name":"Rect1"},{"Name":"Rect2"}]

这是意料之中的,鉴于序列化程序认为它们都是“形状”,我​​怎样才能使它足够聪明,可以序列化到适当的子类

【问题讨论】:

标签: c# json .net system.text.json


【解决方案1】:

如果改变你的基类,你可以让你的代码更简单

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

在这种情况下,您可以以更简单和安全的方式启动对象。我也推荐使用 Newtonsoft.Json。它会让你的生活更轻松

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);

结果

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

【讨论】:

    猜你喜欢
    • 2012-12-10
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多