1

Imagine I have a class like this one:

public class Foo
{
    [JSonProperty("a")]
    public int a;

    [JSonProperty("b")]
    public int b;

    public List<Foo> foos;
}

and imagine I have a Json like this one:

{
"a": "0",
"b": "1",
"moreFoos": {
    "total" : "2",
    "foos" : [
        {
            "a" : "2",
            "b" : "3"
        }, 
        {
            "a" : "4",
            "b" : "5"
        }
    ]
}
}

So, what I want to do is to deserialize with JsonConvert.DeserializeObject(Foo) all properties, but right now only "a" and "b" are deserialized. I have tried to put something like this on foos property:

[JsonProperty("moreFoos.foos")]
public List<Foo> foos;

but it does not work, foos is null. Do you know if there is a way to map properties dynamically this way? Of course, I would like to avoid creating a new class with an int property called "total" and another one called foos as a List of Foo objects.

Regards, Román.

Roman
  • 1,691
  • 4
  • 18
  • 35
  • I can only think of using dynamic here: JsonConvert.DeserializeObject(Foo) and then using a method to convert dynamic to your object. Otherwise you could use a [custom deserializer](http://stackoverflow.com/questions/25897199/deserialize-dynamic-json-file-c-sharp-newtonsoft-json?rq=1) – JasonWilczak May 14 '15 at 15:44
  • IMO, you should create a type that directly maps to the shape of your json data. If you then would prefer a different shape, create a new type for that and map accordingly. – Kirk Woll May 14 '15 at 15:53

1 Answers1

0

One possibility is to serialize the list in a private nested proxy type, like so:

public class Foo
{
    struct ListWrapper<T>
    {
        public int total { get { return (foos == null ? 0 : foos.Count); } }

        [JsonProperty(DefaultValueHandling=DefaultValueHandling.Ignore)]
        public List<T> foos { get; set; }

        public ListWrapper(List<T> list) : this()
        {
            this.foos = list;
        }
    }

    [JsonProperty("a")]
    public int a;

    [JsonProperty("b")]
    public int b;

    [JsonIgnore]
    public List<Foo> foos;

    [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
    ListWrapper<Foo>? moreFoos
    {
        get
        {
            return foos == null ? null : (ListWrapper<Foo>?)new ListWrapper<Foo>(foos);
        }
        set
        {
            foos = (value == null ? null : value.Value.foos);
        }
    }
}

(I'm using a wrapper struct instead of a class to avoid a problem where ObjectCreationHandling is set to Reuse, in which the proxy wrapper class is never set back after being gotten and filled in.)

Another option would be to use a JsonConverter to dynamically restructure your data, along the lines of Can I serialize nested properties to my class in one operation with Json.net?, but tweaked because your class is recursive.

dbc
  • 104,963
  • 20
  • 228
  • 340