Reputation: 23
I would like to know if there is a way to get a specific directory structure and parse it to json so I can create a client-side treeview schema using a jquery plugin. thanks in advance
Upvotes: 1
Views: 3882
Reputation: 1600
In fact, there is an easy way to convert a C# object to JSON using Json.NET.
You simply create a List<>
that contains the data you want and then call
var wrapper = new { TreeData= list };
string json = JsonConvert.SerializeObject(wrapper);
Upvotes: 1
Reputation: 79441
Using JSON.NET:
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()
});
}
Example usage:
var json = GetDirectory(new DirectoryInfo("...some path...")).ToString();
This will give you JSON that looks something like this:
{
"directory":
{
"dirA": {
"file" : [ "file0.txt", "file1.jpg" ]
},
"emptyDir": {
}
},
"file": [ "file2.png" ]
}
Upvotes: 6
Reputation: 16963
You can create custom classes like:
abstract class DirectoryChildItem
{
public string Name { get; set; }
}
class Directory : DirectoryChildItem
{
public List<DirectoryChildItem> Childs { get; set; }
}
class File : DirectoryChildItem
{
}
Then you should traverse your file system using static class System.IO.Directory and create items using classes above. After traversing file system use "return Json(obj)" method in your ASP.NET MVC action
Upvotes: -1