如何使用 json.net 对 json 进行递归下降? [英] How to do recursive descent of json using json.net?
问题描述
我正在尝试使用 json.net 解析 json 文件.文件看起来像这样
I am trying to parse a json file using json.net. The file looks like this
{X:
{
Title:"foo",
xxxx:xxxx
}
}
{Y:
{ZZ:
{Title: "bar",...}
}
}
我试图递归处理所有具有 Title 属性的对象的结构.但我对 JToken
、JProperty
、JContainer
、JValue
、JObject
感到困惑.阅读源代码并没有让我变得更聪明,而且没有任何示例有帮助.我想要一些类似
I am trying to recurse down this structure processing all objects with a Title attribute. But I am confused about JToken
, JProperty
, JContainer
, JValue
, JObject
. Reading the source code has not left me much wiser and none of the samples help. I want something along the lines of
WalkNode(node, Action<Node> action)
{
foreach(var child in node.Children)
{
Action(child);
WalkNode(child);
}
}
Parse()
{
WalkNode(root, n=>
{
if(n["Title"] != null)
{
...
}
});
}
推荐答案
下面的代码应该与您要查找的内容非常接近.我假设有一个外部数组,并且数组可以出现在层次结构中的任何位置.(如果这不是真的,您可以稍微简化 WalkNode 方法代码,但它应该可以工作.)
The code below should be pretty close to what you are looking for. I made the assumption that there is an outer array, and that arrays can appear anywhere in the hierarchy. (If this is not true, you can simplify the WalkNode method code a bit, but it should work either way.)
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace JsonRecursiveDescent
{
class Program
{
static void Main(string[] args)
{
string json =
@"[
{
""X"":
{
""Title"":""foo"",
""xxxx"":""xxxx""
}
},
{
""Y"":
{
""ZZ"":
{
""Title"":""bar"",
""xxxx"":""xxxx""
}
}
}
]";
JToken node = JToken.Parse(json);
WalkNode(node, n =>
{
JToken token = n["Title"];
if (token != null && token.Type == JTokenType.String)
{
string title = token.Value<string>();
Console.WriteLine(title);
}
});
}
static void WalkNode(JToken node, Action<JObject> action)
{
if (node.Type == JTokenType.Object)
{
action((JObject)node);
foreach (JProperty child in node.Children<JProperty>())
{
WalkNode(child.Value, action);
}
}
else if (node.Type == JTokenType.Array)
{
foreach (JToken child in node.Children())
{
WalkNode(child, action);
}
}
}
}
}
这篇关于如何使用 json.net 对 json 进行递归下降?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!