我正在尝试使用C#将文件夹结构动态映射为JSON格式。
以下是我的方法:
public static string StartJson(string Dir)
{
try
{
StringBuilder Json = new StringBuilder();
Json.Append("{\"FileSystem\" : [");
if (Directory.GetDirectories(Dir).ToList().Count > 0)
{
Json.Append(GetDirectoryJson(Dir, 0));
}
if(Directory.GetFiles(Dir).ToList().Count > 0 && Directory.GetDirectories(Dir).ToList().Count == 0)
{
Json.Append(GetFileJSON(Dir));
}
else if(Directory.GetFiles(Dir).ToList().Count > 0 && Directory.GetDirectories(Dir).ToList().Count > 0)
{
Json.Append(",");
Json.Append("{");
Json.Append(GetFileJSON(Dir));
Json.Append("}");
}
Json.Append("]}");//Close FileSystem
return Json.ToString();
}
catch(Exception e) { return ""; }
}
public static int count = 0;
public static string GetDirectoryJson(string Dir, int Iteration)
{
try
{
string path1 = Directory.GetParent(Dir).FullName;
bool p = path.Equals(Directory.GetParent(Dir).FullName);
StringBuilder Json = new StringBuilder();
int folders = Directory.GetDirectories(path).ToList().Count;
foreach (string DirectoryPath in Directory.GetDirectories(Dir))
{
Json.Append("{");
Json.Append("\"Folder\": [{");
Json.Append("\"FolderPath\": " + "\"" + DirectoryPath.Replace('\\', '/') + "\"");
if(Directory.GetDirectories(DirectoryPath).ToList().Count > 0)
{
Json.Append(",");
Json.Append("\"Sub\": [");
count++;
Json.Append(GetDirectoryJson(DirectoryPath, Iteration++));
Json.Append("]");
}
if (Directory.GetFiles(DirectoryPath).ToList().Count > 0)
{
Json.Append(",");
Json.Append(GetFileJSON(Dir));
}
Json.Append("}");
Json.Append("]");
Json.Append("}");
}
return Json.ToString();
}
catch (Exception e) { return "Fail"; }
}
public static string GetFileJSON(string Dir)
{
try
{
StringBuilder Json = new StringBuilder();
Json.Append("\"Files\": [");
int FileCount = 0;
foreach (string FilePath in Directory.GetFiles(Dir))
{
Json.Append("{\"FilePath\": " + "\"" + FilePath.Replace('\\', '/') + "\"");
FileCount++;
if (Directory.GetFiles(Dir).ToList().Count == FileCount)
Json.Append("}");
else
Json.Append("},");
}
Json.Append("]");
return Json.ToString();
}
catch(Exception e) { return ""; }
}
我非常接近,因为当我使用我的测试文件夹时,这会发出大致正确的JSON:"C:\Users\sredmond.QPS_DOMAIN\Documents\Test"
我得到以下JSON:
{
"FileSystem":[
{
"Folder":[
{
"FolderPath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1",
"Sub":[
{
"Folder":[
{
"FolderPath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files",
"Sub":[
{
"Folder":[
{
"FolderPath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/images",
"Files":[
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/CheckBrowser.js.download"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/footer_right.jpg"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/ga.js.download"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/igpnl_up.gif"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/ig_panel.css"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/ig_shared.css"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/jquery-1.9.0.min.js.download"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/jquery.browser.js.download"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/jquery.cookie.js.download"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/qps_logo.png"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/QPS_New.css"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/ScriptResource(1).axd"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/ScriptResource(2).axd"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/ScriptResource(3).axd"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/ScriptResource(4).axd"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/ScriptResource.axd"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/secondaryNavBG_right.jpg"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/WebResource.axd"
}
]
}
]
}
],
"Files":[
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin.html"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/UsersAndPass.csv"
}
]
}
]
}
],
"Files":[
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/New Hire Reporting Form - Copy.pdf"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/New Hire Reporting Form.pdf"
}
]
}
]
} {
"Folder":[
{
"FolderPath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub2",
"Sub":[
{
"Folder":[
{
"FolderPath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub2/Test",
"Files":[
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub2/UsersAndPass - Big (737).csv"
}
]
}
]
}
],
"Files":[
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/New Hire Reporting Form - Copy.pdf"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/New Hire Reporting Form.pdf"
}
]
}
]
} {
"Folder":[
{
"FolderPath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub3"
}
]
},
{
"Files":[
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/New Hire Reporting Form - Copy.pdf"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/New Hire Reporting Form.pdf"
}
]
}
]
}
正如您所看到的,JSON几乎是正确的,但没有逗号分隔在Root上找到的文件夹。您可以将JSON放在此处:https://jsonformatter.curiousconcept.com/并亲自查看错误发生的位置。
无论如何,我的问题是如何制作它以便将这些逗号放在正确的位置。每当我尝试添加逗号或在其中添加条件时,都会将逗号放在JSON中的随机位置。
答案 0 :(得分:7)
不要通过字符串操作创建一个json ...
我会创建一个自定义类文件夹并使用递归方法
public class Folder
{
public string Path { set; get; }
public List<string> Files { set; get; }
public List<Folder> SubFolders { set; get; }
}
Folder GetFolderHierarchy(string root)
{
var folder = new Folder();
var dir = new DirectoryInfo(root);
folder.Path = root;
folder.Files = dir.GetFiles().Select(x => x.FullName).ToList();
folder.SubFolders = dir.GetDirectories().Select(x => GetFolderHierarchy(x.FullName))
.ToList();
return folder;
}
现在,您可以将其称为
var folder = GetFolderHierarchy(@"d:\temp");
var json = JsonConvert.SerializeObject(folder, Newtonsoft.Json.Formatting.Indented);
<强> ADDITION 强>
如果您想存储相对路径而不是完整路径,则可以将方法更改为:
Folder GetFolderHierarchy(string root)
{
var folder = new Folder();
var dir = new DirectoryInfo(root);
folder.Files = dir.GetFiles().Select(x => x.Name).ToList();
folder.Path = dir.Name;
folder.SubFolders = dir.GetDirectories().Select(x => GetFolderHierarchy(x.FullName))
.ToList();
return folder;
}
答案 1 :(得分:1)
问题隐藏在最后Json.Append("}")
的 GetDirectoryJson 中
您需要在同一级别的目录之间添加逗号。如果你有一个更广泛的目录树,你会看到更多的逗号问题。
话虽如此,正如所建议的那样,您最好使用已经过许多测试和使用的完善的库,例如JSON.Net
答案 2 :(得分:0)
谢谢你们的回复。在深入了解JSON.NET之后,我在这里找到了一个很好的答案:Is there a way to directly get a directory structure and parse it to Json in C#?