0

我正在尝试按顺序将 Json 对象反序列化为动态列表,所以我有:

杰森:

   string json = "{'elements':[
                     {'EntityA':[
                               {'name ':'Jhon'}
                               ],
                      'EntityB':[
                               {'title' : 'car'}
                               ],
                      'EntityB':[
                               {'title':'aaa'}
                               ],
                      'EntityA':[
                               {'name' : 'Alice'}
                               ]]}";

.NET 类基类:

public interface EntitysInterface{}

public class EntityA: EntitysInterface
{
   public string name { get; set; }
}

public class EntityB: EntitysInterface
{
   public string title { get; set; }
}

public class Entitys
{
    public List<EntitysInterface> elements { get; set; } //EntityA, EntityB,...

    public Entitys() 
    {
    }
}

我的反序列化对象困难:

Entitys listFinaly = JsonConvert.DeserializeObject<Entitys>(json); 

异常“类型是接口或抽象类,无法实例化。:(”

4

1 回答 1

2

JSON.NET 反序列化器告诉您它无法确定EntitysInterface您想要选择哪个对象。它需要你给它一个提示。

ContractResolver有助于给出提示。

这篇文章回答了一个类似的问题。

编辑:

JSON.Net 文档中有一个很好的示例。

于 2013-01-10T23:33:16.633 回答