Search code examples
c#asp.netjsondynatree

Converting a directory structure and parsing to JSON format in C#


I want to get the directory structure on server and parse it to json format so that I can send this to jQuery treeview plugin(Dynatree) through ajax. Dynatree accepts tree data something like this:

[
{"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"}
]

In this Question @Timothy Shields shown a way to get Directory from DirectryInfo class and parse the structure to Json format like this:

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()
});
}

but the output is not like the above one and I don't know how can I manipulate it. I would appreciate if someone tell how I can produce above output from directory structure. Thanks.

Edit:
I have edited the question. I think the question is clear now.


Solution

  • try this instead : you could create a class with properties as Dynatree want (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 DynatreeToJson()
        {
            return JsonConvert.SerializeObject(this, Formatting.Indented);
        }
    }
    

    The method "DynatreeToJson" return a string formatted in Json as Dynatree waits for it. This is an example to use the DynatreeItem class :

    DynatreeItem di = new DynatreeItem(new DirectoryInfo(@"....Directory path...."));
    string result = "[" + di.DynatreeToJson() + "]";