简体   繁体   English

C#JSON.net NewtonSoft无法正确转换对象继承

[英]C# JSON.net NewtonSoft not converting object inheritence correctly

I am trying to serialize and deserialize inheriting objects in a dictionary using JSON.net NewtonSoft. 我正在尝试使用JSON.net NewtonSoft对字典中的继承对象进行序列化和反序列化。

In my program I have 3 classes setup A , B and C . 在我的程序中,我有3个类,分别是ABC Both B and C inherit A : BC都继承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;
}

In my code I create a dictionary which can story objects inheriting A and fill it with a B and a C object. 在我的代码中,我创建了一个字典,该字典可以讲述继承A对象,并用BC对象填充它。

When I try using the objects in the dictionary, C# still knows the objects are of their type. 当我尝试使用字典中的对象时,C#仍然知道对象是其类型的。 (see code below) (请参见下面的代码)

But after serializing and deserializing, C# doesn't understand that it has to treat the B and C object in the dictionary as B and C objects. 但是,序列化和反序列化后,C#不明白,它具有治疗BC对象在词典中BC对象。

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();
}

Output: 输出:

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

How do I let NewtonSoft know it should serialize the objects correctly with their correct type? 我如何让NewtonSoft知道应该使用正确的类型正确序列化对象?

So that the last two write lines will write the same as the first two. 这样后两行的写操作将与前两行相同。

Passing the same settings to the DesirializeObject will solve this issue. 将相同的设置传递给DesirializeObject将解决此问题。

Sorry for bothering. 很抱歉打扰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM