0

I have a class with properties like this:

    [JsonProperty("property_name")]
    public string PropertyName { get; internal set; }

and I then use [JObject].ToObject<Class>() to populate the properties on the class. This works fine in general, but some of the properties in the JObject are several levels down. For example, they would be accessed via items.first_group.property. However, if I try setting the JsonProperty's PropertyName to that, e.g.

[JsonProperty("monkeyOne.name")]

it simply doesn't set the value. Am I just doing something wrong, or is it really not possible to do this? And if not, is there a reason or has it just not been implemented?

1 Answers1

0

When you say it is 'several levels down', it suggests there is no property 'monkeyOne.name'.

There may be a property 'monkeyOne' that is an object with a property 'name', but that is an entirely different thing.

ToObject can only be used if the overall structure of the JObject matches the class structure.

Phil Degenhardt
  • 7,215
  • 3
  • 35
  • 46
  • Yeah I know how to use it when it matches the class structure, but it seems like a bit of an oversight not to be able to go several levels in. (E.g. you *can* do `.SelectToken("monkey_one.name"`). This is especially true because I might not *want* to create several "monkey" classes and have them eating up memory when all I really want is the name of each monkey. –  Feb 01 '16 at 22:19
  • The path to a token is an entirely different thing to a property name. If you believe it is an oversight, you can raise it here: https://github.com/JamesNK/Newtonsoft.Json/issues – Phil Degenhardt Feb 02 '16 at 01:14
  • Also, you can work directly with JObject (without deserialising to a matching C# class) by casting it as `dynamic`. You could then have code to map from JObject to your desired C# object. Some examples here: http://weblog.west-wind.com/posts/2012/Aug/30/Using-JSONNET-for-dynamic-JSON-parsing – Phil Degenhardt Feb 02 '16 at 01:17