给出以下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是抽象的。
JsonConvert.Deserialize<IEnumerable<BaseClass>>()
BaseClass
你需要:
JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }; string strJson = JsonConvert.SerializeObject(instance, settings);
所以JSON看起来像这样:
{ "$type": "System.Collections.Generic.List`1[[MyAssembly.BaseClass, MyAssembly]], mscorlib", "$values": [ { "$id": "1", "$type": "MyAssembly.ClassA, MyAssembly", "Email": "me@here.com", }, { "$id": "2", "$type": "MyAssembly.ClassB, MyAssembly", "Email": "me@here.com", } ] }
然后您可以反序列化它:
BaseClass obj = JsonConvert.DeserializeObject<BaseClass>(strJson, settings)
文档: TypeNameHandling设置