The hierarchy you are looking at is how Json.net structures objects, it is not representative of the json string itself.
Regarding the ProductA object (well, one up), here's how you go to ProductC :
JProperty: "ProductA" -> JObject (ProductA object) -> JProperty: "children" -> JObject (children object) -> JProperty: "ProductC" -> JObject (ProductC object) *you are here
So, if you look at it this way, you will see that you are actually accessing JProperty "ProductA" (5 parents), and not the object itself. As you may have noticed, JObject has no name, you get the name JProperty .
I can’t tell you exactly how you can access it, as described in the json line, this is not like an option. But you could, of course, write some helper methods to get them for you.
Here is one implementation for getting the parent object. I do not know what other JTokens we will meet that we want to miss, but this is the beginning. Just go to the token you want to receive from the parent. Go to the optional parent number to indicate which parent you want.
JToken GetParent(JToken token, int parent = 0) { if (token == null) return null; if (parent < 0) throw new ArgumentOutOfRangeException("Must be positive"); var skipTokens = new[] { typeof(JProperty), }; return token.Ancestors() .Where(a => skipTokens.All(t => !t.IsInstanceOfType(a))) .Skip(parent) .FirstOrDefault(); }
source share