【发布时间】:2019-10-17 11:09:11
【问题描述】:
概述:
我正在使用 ASP.NET Web API 2 构建一个 API。我正在使用 SQL 构建存储过程并在 API 中链接这些以提供数据。
例如,我知道 SQL 可以使用 FOR JSON AUTO 返回 JSON。但是,我认为这不是配置数据和输出JSON 的最佳位置。所以我假设必须有一种方法可以在 API 中实现嵌套 JSON。
这就是我想要实现的目标:
{
"Apps": [
{
"ItemID": "1",
"Path": "/AppReport",
"Name": "AppReport",
"Reports": [
{
"Reports_ItemID": "11",
"Reports_Path": "/AppReport/SubReport",
"Reports_Name": "SubReport"
},
{
"Reports_ItemID": "12",
"Reports_Path": "/AppReport/SubReport2",
"Reports_Name": "SubReport2"
}
]
},
{
"ItemID": "2",
"Path": "/AppReport2",
"Name": "AppReport2",
"Reports": [
{
"Reports_ItemID": "22",
"Reports_Path": "/AppReport/SubReport",
"Reports_Name": "SubReport"
}
]
}
]
}
目前它以Array of Objects 的形式推出
{
"Apps": [
{
"ItemID": "1",
"Path": "/AppReport",
"Name": "AppReport",
"Reports_ItemID": "11",
"Reports_Path": "/AppReport/SubReport",
"Reports_Name": "SubReport"
},
{
"ItemID": "1",
"Path": "/AppReport",
"Name": "AppReport",
"Reports_ItemID": "12",
"Reports_Path": "/AppReport/SubReport2",
"Reports_Name": "SubReport2"
},
...
]
}
我在 API 中有一个存储过程类,如下所示:
namespace API.Stored_Procedures
{
public partial class SP_GetApps
{
public System.Guid ItemID { get; set; }
public string Path { get; set; }
public string Name { get; set; }
public System.Guid Report_ItemID { get; set; }
public string Report_Path { get; set; }
public string Report_Name { get; set; }
}
}
我的控制器如下所示:
[HttpGet]
[Route("{uid}", Name ="getReportApps")]
[ResponseType(typeof(SP_GetApps_Result))]
public IHttpActionResult SP_GetApps(string uid)
{
var res = db.Database.SqlQuery<SP_GetApps_Result>
("SP_GetApps {0}", uid);
return Ok(res);
}
【问题讨论】:
-
你不能让你的方法返回 JsonResult ......比如 `return Ok(new JsonResult(res))' 并将 Report_itemId、Path 和 Name 作为另一个类,然后 SP_GetApps 将有列表一个新的类......这样你的控制会给你所有
-
@Veljko89 抱歉,我对 C# 不是很有经验,请您帮忙详细说明一下。
标签: c# asp.net json sql-server