如何使用Newtonsoft JSON.NET将JSON反序列化为IEnumerable

给出以下JSON:


[

  {

    "$id": "1",

    "$type": "MyAssembly.ClassA, MyAssembly",

    "Email": "me@here.com",

  },

  {

    "$id": "2",

    "$type": "MyAssembly.ClassB, MyAssembly",

    "Email": "me@here.com",

  }

]

和这些类:


public abstract class BaseClass

{

    public string Email;

}

public class ClassA : BaseClass

{

}

public class ClassB : BaseClass

{

}

如何将JSON反序列化为:


IEnumerable<BaseClass> deserialized;

我不能使用,JsonConvert.Deserialize<IEnumerable<BaseClass>>()因为它抱怨那BaseClass是抽象的。


泛舟湖上清波郎朗
浏览 688回答 3
3回答

慕雪6442864

你需要:&nbsp;JsonSerializerSettings settings = new JsonSerializerSettings&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;TypeNameHandling = TypeNameHandling.All&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;};string strJson = JsonConvert.SerializeObject(instance, settings);所以JSON看起来像这样:{&nbsp; "$type": "System.Collections.Generic.List`1[[MyAssembly.BaseClass, MyAssembly]], mscorlib",&nbsp; "$values": [&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; "$id": "1",&nbsp; &nbsp; &nbsp; "$type": "MyAssembly.ClassA, MyAssembly",&nbsp; &nbsp; &nbsp; "Email": "me@here.com",&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; "$id": "2",&nbsp; &nbsp; &nbsp; "$type": "MyAssembly.ClassB, MyAssembly",&nbsp; &nbsp; &nbsp; "Email": "me@here.com",&nbsp; &nbsp; }&nbsp; ]}然后您可以反序列化它:BaseClass obj = JsonConvert.DeserializeObject<BaseClass>(strJson, settings)

侃侃无极

反序列化时使用以下JsonSerializerSettings构造:new JsonSerializerSettings(){&nbsp; &nbsp; TypeNameHandling = TypeNameHandling.Objects})
打开App,查看更多内容
随时随地看视频慕课网APP