json.net 反序列化 - 如何为图中的子对象指定转换器?
我正在尝试使用 json.net 反序列化一个带有几个子对象的对象。
我有一个自定义转换器来转换 Duty,它继承自 BaseDuty 类及其任务,在调用时工作正常
JsonConvert.Deserialize<Duty>(json, new CustomJsonConverter());
但是,在调用
JsonConvert.Deserialize<Person>(json,new CustomJsonConverter());
自定义 json 转换器的 CanConvert 时会触发...但不会像调用时那样进行验证它是为它编写的类。最终发生的事情是它不断转换为基类,这不是我想要做的,因为转换器正确地转换了它。
所以,我的问题是为如下图中的子对象指定转换器的最佳方法是什么?
下面是一个例子:
public class Person
{
public virtual string Name { get; set; }
public virtual IList<Occupation> Occupations { get;set;}
public virtual IList<RandomProperty> RandomProperties {get;set;}
}
public class Occupation
{
public IList<Duty> Duties {get;set;}
}
public class Duty : BaseDuty
{
public IList<Task> Tasks {get;set;}
}
public class BaseDuty
{
public string Name {get;set;}
}
谢谢
I'm trying to work through deserializing using json.net an object with a few children.
I have a custom converter to convert Duty which inherits from BaseDuty class with it's Tasks, which works fine when called with
JsonConvert.Deserialize<Duty>(json, new CustomJsonConverter());
However, when calling
JsonConvert.Deserialize<Person>(json,new CustomJsonConverter());
the custom json converter's CanConvert does fire...but doesn't validate as it would when called on against the class it was written for. And what ends up happening is it keeps converting to the base class, which is not what i want to do as the converter correctly converts it.
So, my question is what's the best way to specify the converters for child objects in a graph like below?
Below is an example:
public class Person
{
public virtual string Name { get; set; }
public virtual IList<Occupation> Occupations { get;set;}
public virtual IList<RandomProperty> RandomProperties {get;set;}
}
public class Occupation
{
public IList<Duty> Duties {get;set;}
}
public class Duty : BaseDuty
{
public IList<Task> Tasks {get;set;}
}
public class BaseDuty
{
public string Name {get;set;}
}
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如何使用 JsonConverterAttribute 来注释 Duty 类 - 例如,
How about using JsonConverterAttribute to annotate Duty class - for example,