I have the following JSON document stored in a text file
{
"attributes": {"attr0":"value0"},
"children" : {
"ProductA" : {
"attributes": {"attr1":"value1", "attr2":"value2"},
"children" : {
"ProductC":{
"attributes": {"attr3":"value3", "attr4":"value4"},
"children" : {},
"referencedChildren" : {}
}
},
"referencedChildren" : {}
},
"ProductB" : {
"attributes": {"attr5":"value5", "attr6":"value6"},
"children" : {},
"referencedChildren" : {}
}
},
"referencedChildren" : {}
}
I have written this code in C# using NewtonSoft JSon.NET Library
string content = File.ReadAllText(@"c:\temp\foo.txt");
JToken token = JToken.Parse(content);
JToken p2 = token["children"]["ProductA"]["children"]["ProductC"];
This works and I get the node for p2
.
However if I want the node for ParentA
from the p2
node. I have to say
JToken p1 = p2.Parent.Parent.Parent.Parent.Parent;
Console.WriteLine(((JProperty)p1).Name);
The code above prints "ProductA"
. But the the confusing part is that why do I have to call parent 5 times.
When I look at my document, I can see that "children"
is the parent of "ProductC"
and then "ProductA"
is the parent of children. Therefore 2 calls to Parent
should have got me ParentA
.
Why do I need 5 calls?