我使用Json。Net并尝试序列化和反序列化包含多种类型对象的List。我正在努力寻找一种方法来结束一个包含我的派生类型的对象的List,而不是结束一个基类型的列表。
我的代码示例让它很清楚发生了什么:
public class Vehicle{
public int wheels = 4;
}
public class Truck : Vehicle {
public int airhorns = 1;
}
static void Main (string[] args) {
List<Vehicle> vehicles = new List<Vehicle> ();
vehicles.Add (new Vehicle ());
vehicles.Add (new Truck ());
foreach (Vehicle v in vehicles) {
Console.WriteLine ("Before deserializing, we have a: " + v.GetType ());
}
string s = JsonConvert.SerializeObject (vehicles);
List<Vehicle> deserialized = JsonConvert.DeserializeObject<List<Vehicle>> (s);
foreach (Vehicle v in deserialized) {
Console.WriteLine ("After deserializing, we have a: " + v.GetType ());
}
}
运行这个命令的结果是:
Before deserializing, we have a: Vehicle
Before deserializing, we have a: Truck
After deserializing, we have a: Vehicle
After deserializing, we have a: Vehicle
我想在我的反序列化列表中以一辆卡车结束。需要注意的一点是,字符串"s"中的json确实包含airhorns变量。所以数据是存在的
我已经浏览了JSON文档,并没有找到任何我正在寻找的东西。我研究了黑客CustomCreationConverters (http://james.newtonking.com/json/help/index.html?topic=html/CustomCreationConverter.htm),它们似乎可以潜在地用于实例化正确的派生类,但该方法不提供任何json数据,所以我无法确定类型。
我愿意添加另一个可能显式定义"Class:Vehicle"或"Class:Truck"的字段,尽管我还不确定如何使用它。也许在创建了正确的类之后,我可以JsonConvert。PopulateObject在新对象上…但是我需要处理json片段。
任何想法?谢谢!
设置TypeNameHandling
,并在序列化和反序列化中使用此设置。
var settings = new JsonSerializerSettings() {
TypeNameHandling = Newtonsoft.Json.TypeNameHandling.All
};
string s = JsonConvert.SerializeObject(vehicles, settings);
List<Vehicle> deserialized = JsonConvert.DeserializeObject<List<Vehicle>>(s,settings);
foreach (Vehicle v in deserialized)
{
Console.WriteLine("After deserializing, we have a: " + v.GetType());
}
输出:Before deserializing, we have a: SO3.Form1+Vehicle
Before deserializing, we have a: SO3.Form1+Truck
After deserializing, we have a: SO3.Form1+Vehicle
After deserializing, we have a: SO3.Form1+Truck