使用newtonsoft.json反序列化List <AbstractClass>

L.T*_*hin 11 .net c# vb.net serialization json.net

我正在尝试序列化和反序列化一个abstract类列表(mustinherit对于vb),其中只有派生类的实例.

我已经使用JsonProperty(ItemTypeNameHandling = TypeNameHandling.Auto)获得如下所示的输出来装饰list参数:

但是当我反序列化时,它一直说他不能反序列化抽象类.

http://james.newtonking.com/json/help/index.html?topic=html/SerializeTypeNameHandling.htm

public class ConcreteClass
{
    private ObservableCollection<AbstractClass> _Nodes = new ObservableCollection<AbstractClass>();
    //<Newtonsoft.Json.JsonProperty(itemtypenamehandling:=Newtonsoft.Json.TypeNameHandling.Auto)>
    public ObservableCollection<AbstractClass> Nodes {
        get { return this._Nodes; }
    }
    public string Name { get; set; }
    public int Id { get; set; }
}

public abstract class AbstractClass
{
    private ObservableCollection<AbstractClass> _Nodes = new ObservableCollection<AbstractClass>();
    [Newtonsoft.Json.JsonProperty(itemtypenamehandling = Newtonsoft.Json.TypeNameHandling.Auto)]
    public ObservableCollection<AbstractClass> Nodes {
        get { return this._Nodes; }
    }
}
Run Code Online (Sandbox Code Playgroud)

删除它起作用的注释行!

Tim*_*ers 16

根据文档,确保在反序列化时指定TypeNameHandling:

// for security TypeNameHandling is required when deserializing
Stockholder newStockholder = JsonConvert.DeserializeObject<Stockholder>(jsonTypeNameAuto, new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.Auto
});
Run Code Online (Sandbox Code Playgroud)

值得注意的是,文档正在反序列化包含 Abstract类集合的Concrete 类.

作为一个实验,尝试创建一个抛弃类(具体),它具有一个带有抽象对象列表的单个属性,并查看是否可以对其进行序列化和反序列化.

更新:

我刚刚在LINQPad中测试了以下代码:

void Main()
{
    var test = new List<Business>();
    test.Add(new Hotel { Name = "Hilton", Stars = 5 });
    test.Add(new Pool { Name = "Big Splash", Capacity = 500 });

    test.Dump();

    string json = JsonConvert.SerializeObject(test, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings
    {
        TypeNameHandling = TypeNameHandling.All
    });

    json.Dump();

    var businesses = JsonConvert.DeserializeObject<List<Business>>(json, new JsonSerializerSettings
    {
        TypeNameHandling = TypeNameHandling.All
    });

    businesses.Dump();
}

// Define other methods and classes here
public abstract class Business
{
    public string Name { get;set; }
}
public class Hotel : Business
{
    public int Stars { get;set; }
}
public class Pool : Business
{
    public int Capacity { get;set;}
}
Run Code Online (Sandbox Code Playgroud)

它工作得很好.抽象集合序列化为:

{
  "$type": "System.Collections.Generic.List`1[[UserQuery+Business, query_jvrdcu]], mscorlib",
  "$values": [
    {
      "$type": "UserQuery+Hotel, query_jvrdcu",
      "Stars": 5,
      "Name": "Hilton"
    },
    {
      "$type": "UserQuery+Pool, query_jvrdcu",
      "Capacity": 500,
      "Name": "Big Splash"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

原始和反序列化的集合匹配.