【发布时间】: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 也被序列化?我将如何处理接口多态性?
【问题讨论】:
-
只需要序列化,还是还需要de序列化?
-
理想情况下,@dbc
-
那就看看Is polymorphic deserialization possible in System.Text.Json?和Is there a simple way to manually serialize/deserialize child objects in a custom converter in System.Text.Json?吧。但是如果你只需要序列化,看Why does System.Text Json Serialiser not serialise this generic property but Json.NET does? 更简单。事实上,这看起来像是其中一些或全部的复制品,同意吗?
标签: c# json serialization polymorphism system.text.json