JSON Deserialize complex derived object using Newtonsoft JSON.NET [duplicate]

心已入冬 提交于 2019-12-11 19:33:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!