使用Newtonsoft JSON.NET对复杂的派生对象进行JSON反序列化 [英] JSON Deserialize complex derived object using Newtonsoft JSON.NET

查看:205
本文介绍了使用Newtonsoft JSON.NET对复杂的派生对象进行JSON反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Packet
{
    public Action{get;set;}
}

class Action
{
   string Type;
}

class ConcreteAction1 : Action
{
   base.Type="ConcreteAction1";
}

class ConcreteAction2 : Action
{
   base.Type="ConcreteAction2";
}

我收到Packet类,其中包含来自Action类的各种派生类,默认情况下,每个ConcreteActions都将反序列化为基类Action,但是我希望将它们反序列化为它们的实际类型(ConcreteAction1 ,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?

推荐答案

使用.Parse()将其解析为对象然后进行投射,或者使用.DeserializeObject<T>()将其反序列化为您的对象.然后查看返回值是否正确,如果不正确,请尝试其他操作.或者尝试使用标识符来查看它是哪种具体类型,然后挂接到解串器中.但这可能不是最理想的解决方案.

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.

或者,如果您自己生成JSON,则可以使用设置.

Alternatively, if you are generating the JSON yourself, you can play with the settings.

new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }

序列化时,它将实际的具体类型写入JSON;反序列化时,将其转换为具体类型.

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. :)

这篇关于使用Newtonsoft JSON.NET对复杂的派生对象进行JSON反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆