我认为您可能需要反序列化 Json,然后从那里构造对象。直接反序列化Cat
或Dog
不可能,因为反序列化器不知道如何专门构造这些对象。
编辑:使用 JSON.NET 从反序列化异构 JSON 数组到协变 List<> 中大量借用
像这样的东西会起作用:
interface IAnimal
{
string Type { get; set; }
}
class Cat : IAnimal
{
public string CatName { get; set; }
public string Type { get; set; }
}
class Dog : IAnimal
{
public string DogName { get; set; }
public string Type { get; set; }
}
class AnimalJson
{
public IEnumerable<IAnimal> Items { get; set; }
}
class Animal
{
public string Type { get; set; }
public string Name { get; set; }
}
class AnimalItemConverter : Newtonsoft.Json.Converters.CustomCreationConverter<IAnimal>
{
public override IAnimal Create(Type objectType)
{
throw new NotImplementedException();
}
public IAnimal Create(Type objectType, JObject jObject)
{
var type = (string)jObject.Property("type");
switch (type)
{
case "cat":
return new Cat();
case "dog":
return new Dog();
}
throw new ApplicationException(String.Format("The animal type {0} is not supported!", type));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// Load JObject from stream
JObject jObject = JObject.Load(reader);
// Create target object based on JObject
var target = Create(objectType, jObject);
// Populate the object properties
serializer.Populate(jObject.CreateReader(), target);
return target;
}
}
string json = "{ items: [{ type: \"cat\", catName: \"tom\" }, { type: \"dog\", dogName: \"fluffy\" }] }";
object obj = JsonConvert.DeserializeObject<AnimalJson>(json, new AnimalItemConverter());