我的数据库中有一个文件夹列表,其中包含文件夹列表等,如下所示:
在我的服务方法中检索JSON,我返回一个文件夹列表。
我想收到以下结构:
目前,这是生成文件夹列表的方法:
public List<FolderStructureDTO> GetFolderStructureDTOs()
{
var folders = GetFolders();
foreach (var folder in folders)
{
var bookmarks = db.Bookmarks.OfType<Folder>().Where(x => x.ParentId == folder.Id).ToList();
foreach (var item in bookmarks)
{
folder.FolderBookmarks.Add(item);
}
}
List<FolderStructureDTO> folderDTOs = null;
foreach (var folder in folders)
{
folderDTOs = folders.Select(x => new FolderStructureDTO() { Folder = folder.Name, Subfolders = folder.FolderBookmarks }).ToList();
}
return folderDTOs;
}
public class FolderStructureDTO
{
public string Folder { get; set; }
public List<Bookmark> Subfolders { get; set; }
}
这是我收到的输出JSON:
{"FolderBookmarks":[{"FolderBookmarks":[],"Id":123,"Name":"NonFiction","ParentId":122},{"FolderBookmarks":[{"FolderBookmarks":[],"Id":125,"Name":"Romance","ParentId":124},{"FolderBookmarks":[],"Id":126,"Name":"Horror","ParentId":124}],"Id":124,"Name":"Fiction","ParentId":122}],"Id":122,"Name":"Books","ParentId":101}
为了使它看起来更具可读性,这里是相同的JSON,但使用https://codebeautify.org/jsonviewer
进行了美化:
{
"FolderBookmarks": [
{
"FolderBookmarks": [],
"Id": 123,
"Name": "NonFiction",
"ParentId": 122
},
{
"FolderBookmarks": [
{
"FolderBookmarks": [],
"Id": 125,
"Name": "Romance",
"ParentId": 124
},
{
"FolderBookmarks": [],
"Id": 126,
"Name": "Horror",
"ParentId": 124
}
],
"Id": 124,
"Name": "Fiction",
"ParentId": 122
}
],
"Id": 122,
"Name": "Books",
"ParentId": 101
}
任何人都可以帮我生成所需的JSON格式吗?我环顾四周,无法找到解决方案。