In this article, we will learn how to return nested JSON in C#.
JSON objects are written in key/value pairs. Values in a JSON object can be another JSON object, known as Nested JSON Objects. Accessing nested JSON objects is just like accessing nested arrays.
Let’s take one simple example of creating dynamic menus and submenus.
First, we have to create two SQL tables Menus and SubMenus as given below.
Now create the NestedMenuDTO.cs model class and add the code in it.
using System.Collections.Generic; namespace Nested_JSON.Models { public class NestedMenuDTO { public long Id { get; set; } public string Title { get; set; } public IEnumerable<SubMenu> SubMenuList { get; set; } } }
Open the MenusController.cs file and add the code in it.
// GET: api/Menus [HttpGet] public ActionResult<IEnumerable<NestedMenuDTO>> GetMenus() { List<NestedMenuDTO> nestedMenuList = new List<NestedMenuDTO>(); var menuList = _context.Menus.ToList(); foreach (var menu in menuList) { var nestedMenu = new NestedMenuDTO { Id = menu.Id, Title = menu.Title, SubMenuList = _context.SubMenus.Where(x => x.MenuId == menu.Id).ToList() }; nestedMenuList.Add(nestedMenu); } return nestedMenuList; }
Output:
[ { "id": 1, "title": "Authors", "subMenuList": [ { "id": 1, "title": "Yasin Panwala", "menuId": 1 }, { "id": 2, "title": "Faisal Pathan", "menuId": 1 }, { "id": 6, "title": "Tabish Rangrej", "menuId": 1 } ] }, { "id": 2, "title": "Categories", "subMenuList": [ { "id": 3, "title": ".NET Core", "menuId": 2 }, { "id": 4, "title": "ASP.NET MVC", "menuId": 2 }, { "id": 5, "title": "SQL", "menuId": 2 } ] }, { "id": 3, "title": "Articles", "subMenuList": [] } ]
Please give your valuable feedback and if you have any questions or issues about this article, please let me know.
Also, check How To Read And Write CSV File In C#
please upload the full step by step code uploading only controller and class will not be clear for beginers.
I want to hide menuId in subMenuList, How can i do it ?
Instead of using the SubMenu model of DB context, you have to create and use a custom model class for the SubMenu
public class SubMenuDTO
{
public long Id { get; set; }
public string Title { get; set; }
}