【问题标题】:How to serialize derived classes using polymorphism to JSON如何使用多态性将派生类序列化为 JSON
【发布时间】:2020-11-08 14:58:58
【问题描述】:

如果我有以下课程:

public class ParentClass
{
    public int ParentProperty { get; set; } = 0;
}
public class ChildClass : ParentClass
{
    public string ChildProperty { get; set; } = "Child property";
}
public class Container
{
    public double ContainerCapacity { get; set; } = 0.2;
    public List<ParentClass> ClassContainer { get; set; } = new List<ParentClass>();
}

如果我随后在Program.cs 中创建以下对象:

// Objects
var container = new Container() { ContainerCapacity = 3.14 };
var parent = new ParentClass() { ParentProperty = 5 };
var child = new ChildClass() { ParentProperty = 10, ChildProperty = "value" };
container.ClassContainer.Add(parent);
container.ClassContainer.Add(child);

// Serialization
var serializerOptions = new JsonSerializerOptions() { WriteIndented = true };
var containerJson = JsonSerializer.Serialize(container, serializerOptions);
Console.WriteLine(containerJson);

预期输出:

{
  "ContainerCapacity": 3.14,
  "ClassContainer": [
    {
      "ParentProperty": 5
    },
    {
      "ChildProperty": "value",
      "ParentProperty": 10
    }
  ]
}

实际输出:

{
  "ContainerCapacity": 3.14,
  "ClassContainer": [
    {
      "ParentProperty": 5
    },
    {
      "ParentProperty": 10
    }
  ]
}

如何确保child 上的属性ChildProperty 也被序列化?我将如何处理接口多态性?

【问题讨论】:

标签: c# json serialization polymorphism system.text.json


【解决方案1】:

我在网上看到有关此问题的信息,但似乎不太容易解决。我建议使用 Newtonsoft.Json 库来解析对象,因为它是一个成熟的库,并且可以完美地处理子父对象,而无需编写自定义设置的开销。

Newtonsoft.Json 安装nuget 包,然后像这样解析它:

var containerJson = JsonConvert.SerializeObject(container, Newtonsoft.Json.Formatting.Indented);

输出如下:

{
  "ContainerCapacity": 3.14,
  "ClassContainer": [
    {
      "ParentProperty": 5
    },
    {
      "ChildProperty": "value",
      "ParentProperty": 10
    }
  ]
}

【讨论】:

    猜你喜欢
    • 2017-06-05
    • 2011-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多