我不确定如何序列化/反序列化使用Newtonsoft.JSON实现接口的对象数组
public interface IAnimal {
public int NumLegs { get; set; }
//etc..
}
public class Cat : IAnimal {...}
public class Dog : IAnimal {...}
public class Rabbit : IAnimal {...}
public IAnimal[] Animals = new IAnimal[3] {
new Cat(),
new Dog(),
new Rabbit()
}
如何对Animals
数组进行序列化/反序列化?
尝试这个
IAnimal[] animals = new IAnimal[] {
new Cat{CatName="Tom"},
new Dog{DogName="Scoopy"},
new Rabbit{RabitName="Honey"}
};
var jsonSerializerSettings = new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.All
};
var json = JsonConvert.SerializeObject(animals, jsonSerializerSettings);
List<IAnimal> animalsBack = ((JArray)JsonConvert.DeserializeObject(json))
.Select(o => (IAnimal)JsonConvert.DeserializeObject(o.ToString(),
Type.GetType((string)o["$type"]))).ToList();
测试
json = JsonConvert.SerializeObject(animalsBack, Newtonsoft.Json.Formatting.Indented);
测试结果
[
{
"CatName": "Tom"
},
{
"DogName": "Scoopy"
},
{
"RabitName": "Honey"
}
]
类
public class Cat : IAnimal { public string CatName { get; set; } }
public class Dog : IAnimal { public string DogName { get; set; } }
public class Rabbit : IAnimal { public string RabitName { get; set; } }
public interface IAnimal { }