[英]C# JSON.net NewtonSoft not converting object inheritence correctly
我正在嘗試使用JSON.net NewtonSoft對字典中的繼承對象進行序列化和反序列化。
在我的程序中,我有3個類,分別是A
, B
和C
B
和C
都繼承A
:
public class A
{
public virtual string Value { get; } = "string";
}
public class B : A
{
public override string Value => this.Score.ToString();
public int Score { get; set; } = 5;
}
public class C : A
{
public override string Value => this.AnotherScore.ToString();
public int AnotherScore { get; set; } = 6;
}
在我的代碼中,我創建了一個字典,該字典可以講述繼承A
對象,並用B
和C
對象填充它。
當我嘗試使用字典中的對象時,C#仍然知道對象是其類型的。 (請參見下面的代碼)
但是,序列化和反序列化后,C#不明白,它具有治療B
和C
對象在詞典中B
和C
對象。
static void Main(string[] args)
{
// Create objects to store in dictionary
B b = new B();
A c = (A)new C();
// Store objects in dictionary
var dic = new Dictionary<string, A>();
dic.Add("b", b);
dic.Add("c", c);
// C# still know the objects are of their type
Console.WriteLine(dic["b"].Value);
Console.WriteLine(dic["c"].Value);
// Convert dictionary to JSON
string serialized = JsonConvert.SerializeObject(dic, new JsonSerializerSettings()
{
Formatting = Formatting.Indented,
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
TypeNameHandling = TypeNameHandling.Objects,
});
Console.WriteLine(serialized);
// Convert json to dictionary
var dic2 = JsonConvert.DeserializeObject<Dictionary<string, A>>(serialized);
// C# doesn't know objects are of their type anymore
Console.WriteLine(dic2["b"].Value);
Console.WriteLine(dic2["c"].Value);
Console.ReadKey();
}
輸出:
5
6
{
"$id": "1",
"$type": "System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[TestConsole.A, TestConsole]], mscorlib",
"b": {
"$id": "2",
"$type": "TestConsole.B, TestConsole",
"Value": "5",
"Score": 5
},
"c": {
"$id": "3",
"$type": "TestConsole.C, TestConsole",
"Value": "6",
"AnotherScore": 6
}
}
string
string
我如何讓NewtonSoft知道應該使用正確的類型正確序列化對象?
這樣后兩行的寫操作將與前兩行相同。
將相同的設置傳遞給DesirializeObject將解決此問題。
很抱歉打擾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.