Json.net序列化/反序列化派生types?

json.net(newtonsoft)
我正在浏览文档,但是我找不到任何关于此的最佳方法。

public class Base { public string Name; } public class Derived : Base { public string Something; } JsonConvert.Deserialize<List<Base>>(text); 

现在我已经在序列化列表中派生了对象。 如何反序列化列表并获取派生types?

如果您在text中存储types(就像您在这种情况下那样),您可以使用JsonSerializerSettings

请参阅: 如何使用Newtonsoft JSON.NET将JSON反序列化为IEnumerable <BaseType>

您必须启用types名称处理并将其作为设置parameter passing给(de)序列化程序。

 Base object1 = new Base() { name = "Object1" }; Derived object2 = new Derived() { something = "Some other thing" }; List<Base> inheritanceList = new List<Base>() { object1, object2 }; JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }; string Serialized = JsonConvert.SerializeObject(inheritanceList, settings); List<Base> deserializedList = JsonConvert.DeserializeObject<List<Base>>(Serialized, settings); 

这将导致派生类的正确desirialization。 它的一个缺点是它会命名你使用的所有对象,因此它会命名你放置对象的列表。