开发者

json.net deserializing - how to specify converters for child objects in the graph?

开发者 https://www.devze.com 2023-02-12 05:11 出处:网络
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

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 Occupat开发者_如何学编程ion
    {
        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


How about using JsonConverterAttribute to annotate Duty class - for example,

[JsonConverterAttribute(typeof(CustomJsonConverter))]
public class Duty : BaseDuty
{
   ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消