C# 转换目录结构并解析为 JSON 格式

Dar*_*nce -1 c# asp.net json dynatree

我想获取服务器上的目录结构并将其解析为 json 格式,以便我可以通过 ajax 将其发送到 jQuery treeview 插件(Dynatree)。Dynatree 接受如下树数据:

[
{"title": "Item 1"},
{"title": "Folder 2", "isFolder": true, "key": "folder2",
    "children": [
        {"title": "Sub-item 2.1"},
        {"title": "Sub-item 2.2"}
        ]
    },
{"title": "Folder 3", "isFolder": true, "key": "folder3",
    "children": [
        {"title": "Sub-item 3.1"},
        {"title": "Sub-item 3.2"}
        ]
    },
{"title": "Lazy Folder 4", "isFolder": true, "isLazy": true, "key": "folder4"},
{"title": "Item 5"}
]
Run Code Online (Sandbox Code Playgroud)

在这个问题中,@Timothy Shields 展示了一种从 DirectryInfo 类获取 Directory 并将结构解析为 Json 格式的方法,如下所示:

JToken GetDirectory(DirectoryInfo directory)
{
return JToken.FromObject(new
{
    directory = directory.EnumerateDirectories()
        .ToDictionary(x => x.Name, x => GetDirectory(x)),
    file = directory.EnumerateFiles().Select(x => x.Name).ToList()
});
}
Run Code Online (Sandbox Code Playgroud)

但输出与上面的不同,我不知道如何操作它。如果有人告诉我如何从目录结构生成上述输出,我将不胜感激。谢谢。

编辑:
我已经编辑了问题。我想现在问题已经很清楚了。

小智 5

尝试这样做:您可以创建一个具有 Dynatree 想要的属性的类(标题、isFolder,...)。

class DynatreeItem
{
    public string title { get; set; }
    public bool isFolder { get; set; }
    public string key { get; set; }
    public List<DynatreeItem> children;

    public DynatreeItem(FileSystemInfo fsi)
    {
        title = fsi.Name;
        children = new List<DynatreeItem>();

        if (fsi.Attributes == FileAttributes.Directory)
        {
            isFolder = true;
            foreach (FileSystemInfo f in (fsi as DirectoryInfo).GetFileSystemInfos())
            {
                children.Add(new DynatreeItem(f));
            }
        }
        else
        {
            isFolder = false;
        }
        key = title.Replace(" ", "").ToLower();
    }

    public string DynatreeToJson()
    {
        return JsonConvert.SerializeObject(this, Formatting.Indented);
    }
}
Run Code Online (Sandbox Code Playgroud)

当 Dynatree 等待时,“DynatreeToJson”方法返回一个 Json 格式的字符串。这是使用 DynatreeItem 类的示例:

DynatreeItem di = new DynatreeItem(new DirectoryInfo(@"....Directory path...."));
string result = "[" + di.DynatreeToJson() + "]";
Run Code Online (Sandbox Code Playgroud)