0

I have a list of folders in my database that can contain list of folders and so on like the following:

Folder structure

In my service method to retrieve the JSON, I return a list of folders.

I want to recieve the following structure:

desired json structure

At the moment, this is the method that generates the list of folders:

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

This is the output JSON that I receive:

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

To make it look more readable, here is the same JSON, but beautified using 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
}

Can anyone help me generate the desired JSON format? I've looked around and cannot find a solution.

naz786
  • 485
  • 1
  • 5
  • 22

0 Answers0