C#JSON.net NewtonSoft未正确转换对象继承
我正在尝试使用JSON.net NewtonSoft对字典中的继承对象进行序列化和反序列化 在我的程序中,我有三个类设置C#JSON.net NewtonSoft未正确转换对象继承,c#,json.net,C#,Json.net,我正在尝试使用JSON.net NewtonSoft对字典中的继承对象进行序列化和反序列化 在我的程序中,我有三个类设置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 Sc
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();
}
我如何让NewtonSoft知道它应该以正确的类型正确序列化对象
因此,最后两行写入的内容将与前两行相同。将相同的设置传递给DesiralizeObject将解决此问题
很抱歉打扰您。将相同的设置传递给DesiralizeObject将解决此问题
很抱歉打扰您。您也必须对反序列化程序使用相同的TypeNameHandling设置,我想…@elgonzo Yeah在发布问题后注意到了这一点,谢谢您的帮助!可能重复的你也必须使用相同的反序列化程序的TypeNameHandling设置,我猜…@elgonzo Yeah在发布问题后注意到了这一点,谢谢你的帮助!可能重复的
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