我将以下JSON文档存储在文本文件中
{
"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" : {}
}
Run Code Online (Sandbox Code Playgroud)
我使用NewtonSoft JSon.NET Library在C#中编写了这段代码
string content = File.ReadAllText(@"c:\temp\foo.txt");
JToken token = JToken.Parse(content);
JToken p2 = token["children"]["ProductA"]["children"]["ProductC"];
Run Code Online (Sandbox Code Playgroud)
这有效,我得到了节点p2.
但是,如果我想为节点ParentA从p2节点.我不得不说
JToken p1 = p2.Parent.Parent.Parent.Parent.Parent;
Console.WriteLine(((JProperty)p1).Name);
Run Code Online (Sandbox Code Playgroud)
上面的代码打印出来"ProductA" …