【问题标题】:Parse a json file generated for jstree in C#在 C# 中解析为 jstree 生成的 json 文件
【发布时间】:2016-10-20 15:24:08
【问题描述】:

我希望解析一个动态生成的、没有明确结构的 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”键并检索“它的路径”值。 我试过但没有成功。非常感谢任何帮助。

【问题讨论】:

标签: c# json jstree dynatree


【解决方案1】:

在我看来你的 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);

一旦你反序列化了节点,你需要能够找到你想要的那个。通过在类中引入一个简短的“DescendantsAndSelf”方法,您可以使用 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

【讨论】:

    猜你喜欢
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多