将目录路径转换为 ​​JSON 目录树表示形式

mr.*_*day 3 c# tree json filepath

我有文件路径的示例输出,这只是问题的一个示例

新建文本文档.txt
新建文件夹/
新建文件夹/README.txt

我想将其转换为以下 JSON

{
   "Data":"/",
   "Nodes":[
      {
         "Data":"New Folder",
         "Nodes":[
            {
               "Data":"New Text Document.txt"
            }
         ]
      },
      {
         "Data":"New Text Document.txt",
         "Nodes":[
            ""
         ]
      }
   ]
} 
Run Code Online (Sandbox Code Playgroud)

我的节点类如下

public class Node
    {
        public Node(string fileName)
        {
            Nodes = new List<Node>();
            Data = fileName;
        }

        public List<Node> Nodes { get; set; }

        public string Data { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

我正在尝试找出算法,如何将文件路径表示为 Node 类,稍后我将对其进行序列化以获取 JSON。如果有任何其他方法将文件路径表示为目录树结构 JSON,请建议

Bra*_*d C 5

我终于抽出时间为你制作一个样品。这应该是一个很好可扩展的递归解决方案。:)

static void Main(string[] args)
{
    Node root = new Node("/");
    AddNode("New Text Document.txt", root);
    AddNode("New folder/", root);
    AddNode("New folder/README.txt", root);

    Console.ReadKey();
}

public class Node
{
    public Node() { Nodes = new List<Node>(); }
    public Node(string fileName)
    {
        Nodes = new List<Node>();
        Data = fileName;
    }

    public Node FindNode(string data)
    {
        if (this.Nodes == null || !this.Nodes.Any()) { return null; }

        // check Node list to see if there are any that already exist
        return this.Nodes
            .FirstOrDefault(n => String.Equals(n.Data, data, StringComparison.CurrentCultureIgnoreCase));
    }

    public string Data { get; set; }
    public List<Node> Nodes { get; set; }
}

public static Node AddNode(string filePath, Node rootNode)
{
    // convenience method. this creates the queue that we need for recursion from the filepath for you
    var tokens = filePath.Split('/').ToList();

    // if you split a folder ending with / it leaves an empty string at the end and we want to remove that
    if (String.IsNullOrWhiteSpace(tokens.Last())) { tokens.Remove(""); }

    return AddNode(new Queue<string>(tokens), rootNode);
}

private static Node AddNode(Queue<string> tokens, Node rootNode)
{
    // base case -> node wasnt found and tokens are gone  :(
    if (tokens == null || !tokens.Any())
    {
        return null;
    }

    // get current token, leaving only unsearched ones in the tokens object
    string current = tokens.Dequeue();

    // create node if not already exists
    Node foundNode = rootNode.FindNode(current);
    if (foundNode != null)
    {
        // node exists! recurse
        return AddNode(tokens, foundNode);
    }
    else
    {
        // node doesnt exist! add it manually and recurse
        Node newNode = new Node() { Data = current };
        rootNode.Nodes.Add(newNode);
        return AddNode(tokens, newNode);
    }
}
Run Code Online (Sandbox Code Playgroud)