我想在服务器上获取目录结构并将其解析为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"}
]
在这个Question @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()
});
}
但是输出与上面的输出不一样,我不知道如何操作它。如果有人告诉我如何从目录结构中产生上述输出,我将不胜感激。谢谢。
修改
我编辑了这个问题。我认为现在的问题很清楚了。
答案 0 :(得分:3)
尝试这样做:你可以创建一个具有Dynatree想要属性的类(title,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 JsonToDynatree()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
}
方法“JsonToDynatree”返回一个在Json中格式化的字符串,因为Dynatree正在等待它。 这是使用DynatreeItem类的示例:
DynatreeItem di = new DynatreeItem(new DirectoryInfo(@"....Directory path...."));
string result = "[" + di.JsonToDynatree() + "]";