如果我有以下課程:
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);
Expected output:
{
"ContainerCapacity": 3.14,
"ClassContainer": [
{
"ParentProperty": 5
},
{
"ChildProperty": "value",
"ParentProperty": 10
}
]
}
Actual output:
{
"ContainerCapacity": 3.14,
"ClassContainer": [
{
"ParentProperty": 5
},
{
"ParentProperty": 10
}
]
}
如何確保child
上的屬性ChildProperty
也被序列化?對于接口多態性,我該怎么做呢?
我在網上看到了關于這個問題,似乎不太容易做到。我建議使用
Newtonsoft.Json
庫來解析對象,因為它是一個成熟的庫,可以完美地處理child-parent對象,而無需編寫自定義設置的開銷。為
Newtonsoft.Json
安裝numet包,然后按如下方式進行解析:其輸出如下: