问题
class Packet
{
public Action{get;set;}
}
class Action
{
string Type;
}
class ConcreteAction1 : Action
{
base.Type="ConcreteAction1";
}
class ConcreteAction2 : Action
{
base.Type="ConcreteAction2";
}
I receive Packet
class which contains various derived class from Action
class, by default every ConcreteActions
are deserialized as base class Action
, but I want them to be deserialized as their actual types(ConcreteAction1 ,ConcreteAction2
...)
Is there a way to achieve this?
回答1:
Use .Parse()
to parse it to an object and then cast, or use .DeserializeObject<T>()
to deserialize it to your object. Then see if the return value is correct, if not try something else. Or try to use an identifier to see which of the concrete types it is and hook into the deserializer. But this might not be the most ideal solution.
Alternatively, if you are generating the JSON yourself, you can play with the settings.
new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }
When you serialize it, it will write the actual concrete type into the JSON and when you deserialize it will transform it into the concrete type.
JsonConvert.Deserialize(input, null, settings)
But, perhaps someone has a better idea. :)
来源:https://stackoverflow.com/questions/18427012/json-deserialize-complex-derived-object-using-newtonsoft-json-net