C# Newtonsoft.JSON serialize/deserialize 对象数组
C# Newtonsoft.JSON serialize/deserialize array of objects
我不确定如何处理 serializing/deserializing 使用 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()
}
我将如何处理 serializing/deserializing 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 { }
我不确定如何处理 serializing/deserializing 使用 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()
}
我将如何处理 serializing/deserializing 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 { }