使用newtonsoft.json </abstract class>反序列化List <abstract class>

时间:2013-11-18 01:10:22

标签: c# .net vb.net serialization json.net

我正在尝试序列化和反序列化abstract类列表(mustinherit for 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; }
    }
}

删除它有效的注释行!

1 个答案:

答案 0 :(得分:16)

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

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

值得注意的是,文档正在反序列化包含抽象类集合的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;}
}

完美无缺。抽象集合序列化为:

{
  "$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"
    }
  ]
}

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