解析在C#中为jstree生成的json文件

时间:2016-10-20 15:24:08

标签: c# json jstree dynatree

我希望解析一个动态生成但没有明确结构的JSON文件。

[
  {
    "children": [
      {
        "children": [
          {
            "children": [],
            "text": "Child node 2.txt",
            "isFolder": false,
            "id": "1childnode2.txt",
            "itsPath": "C:\\Users\\pandyapa\\Root node\\Child node 2.txt",
            "type": "itsfile"
          }
        ],
        "text": "Child node 1.txt",
        "isFolder": false,
        "id": "0childnode1.txt",
        "itsPath": "C:\\Users\\pandyapa\\Root node\\Child node 1.txt",
        "type": "itsfile"
      },
      {
        "children": [],
        "text": "Child node 2.txt",
        "isFolder": false,
        "id": "1childnode2.txt",
        "itsPath": "C:\\Users\\pandyapa\\Root node\\Child node 2.txt",
        "type": "itsfile"
      },
      {
        "children": [],
        "text": "Child node 3.txt",
        "isFolder": false,
        "id": "2childnode3.txt",
        "itsPath": "C:\\Users\\pandyapa\\Root node\\Child node 3.txt",
        "type": "itsfile"
      }
    ],
    "text": "Root node",
    "isFolder": true,
    "id": "3rootnode",
    "itsPath": "C:\\Users\\pandyapa\\Root node",
    "type": "default"
  }
]

此JSON可以包含任何嵌套子级。我希望解析每个JSON对象,比较它的“id”键并检索“itspath”值。 我试过但没有成功。任何帮助都非常感谢。

1 个答案:

答案 0 :(得分:0)

在我看来,你的JSON 有一个非常明确的结构,可以用这个递归类来表示:

public class Node
{
    public Node[] Children { get; set; }
    public string Text { get; set; }
    public bool IsFolder { get; set; }
    public string Id { get; set; }
    public string ItsPath { get; set; }
    public string Type { get; set; }
}

可能是JSON可以深度嵌套,你可能不会提前知道每个级别有多少级别或多少个孩子,但事实仍然是每个节点"具有统一的结构。这很好,因为这意味着可以使用Json.Net之类的解析器轻松地对其进行反序列化。实际上,您只需使用一行代码即可完成此操作:

List<Node> nodes = JsonConvert.DeserializeObject<List<Node>>(json);

将序列反序列化后,您需要能够找到所需的节点。通过引入一个简短的&#34; DescendantsAndSelf&#34;在类的方法中,您可以使用LINQ方法使结构可查询。

    public IEnumerable<Node> DescendantsAndSelf()
    {
        yield return this;
        if (Children != null)
        {
            foreach (Node child in Children)
            {
                yield return child;
            }
        }
    }

现在,您可以按ID查找特定节点:

var idToFind = "2childnode3.txt";

var node = nodes.SelectMany(n => n.DescendantsAndSelf())
                .Where(n => n.Id == idToFind)
                .FirstOrDefault();

if (node != null) 
{
    Console.WriteLine(node.ItsPath);
}
else
{
    Console.WriteLine("Not found");
}

小提琴:https://dotnetfiddle.net/u9gDTc