如何从 ASP.Net Web API 中的 SQL table 获取嵌套的 JSON 对象

how to get the nested JSON objects from SQL table in ASP.Net Web API

我需要通过 asp.Net Web API 提供下面提到的 JSON 输出。 此输出将用于在 angular.

中显示组织层次结构(树视图)

我在 SQL table 中有员工数据如下:

EMP_NO  EMP_NAME  DESIGNATION  Manager_ID

需要JSON输出:

 myobject= {
      "parent":[
        {
          "name":"radha Acharya",
          "designation":"General Counsel",
          "state":"",
          "active":false
        },
        {
          "name":"Rakesh mishra",
          "designation":"General Counse2",
          "state":"",
          "active":false
        },
        {
          "name":"Suri patil",
          "designation":"General Counse3",
          "state":"",
          "active":true
        }
      ],
      "childs":[
        {
          "name":"child 1",
          "designation":"Deputy General Counsel",
          "state":"",
          "active":false,
          "hasChilds":true
        },
        {
          "name":"child 2",
          "designation":"Deputy General Counsel",
          "state":"",
          "active":false,
          "hasChilds":true
        },
        {
          "name":"child 3",
          "designation":"Deputy General Counsel",
          "state":"",
          "active":false,
          "hasChilds":false
        },
        {
          "name":"child 4",
          "designation":"Deputy General Counsel",
          "state":"",
          "active":false,
          "hasChilds":true
        },
        {
          "name":"child 5",
          "designation":"Deputy General Counsel",
          "state":"Resigned",
          "active":false,
          "hasChilds":true
        },
        {
          "name":"child 6",
          "designation":"Deputy General Counsel",
          "state":"",
          "active":false,
          "hasChilds":true
        }
      ]
    }

在angular中会这样显示 Front end display image

不确定您打算如何使用 Json,因为父列表和子列表之间没有联系。但是这里是你如何从 SQL 服务器获得 JSON:

#创建 类 类型 parentchild

#创建一个名为 myobject 的对象,其中包含两个 array/list 属性 - parentchilds

#查询SQL DB并填充myobject对象

#将myobject对象转化为JSON并从API动作发送

public class parent
{
    public string name { get; set; } 
    public string designation { get; set; } 
    public string state { get; set; } 
    public bool active { get; set; }
}

public class child
{
    public string name { get; set; } 
    public string designation { get; set; } 
    public string state { get; set; } 
    public bool active { get; set; } 
    public bool hasChilds { get; set; }
}

public class myboject
{
    public List<Parent> parent { get; set; } 
    public List<Child> childs { get; set; }
}

myboject myboj = new myboject();
myboj.parent = new List<Parent>();
myboj.child = new List<Child>();

//查询您的 sql 服务器数据库并使用适当的数据填充 myboj.parentmyboj.child

然后进行Json转换:

return Newtonsoft.Json.JsonConvert.SerializeObject(myboj);

这会将 myObj 转换为 json 对象和 return。