返回控制器MVC中的json路径 [英] Returning json path in controller MVC
问题描述
我有一个返回JSON路径的存储过程:
I have a stored procedure that returns a JSON path :
GO
alter PROCEDURE [dbo].[usp_getjsondata](
@type INT
)
AS
BEGIN
SELECT
[Time] as 'Time',
cast([Value] as varchar(10)) as 'Value'
FROM [dbo].[tbl_data] where type = @type
for JSON PATH
END
在控制器中我写了以下代码:
In the controller i have written the following code:
var json = entities.Database.SqlQuery("exec usp_getjsondata @type",
new SqlParameter("@type", type)
).ToList();
JSON数据未存储在变量JSON中。我在这里遗漏了什么吗?
我尝试过的事情:
我尝试将数据存储在字符串或列表中,但它无法正常工作
The JSON data is not being stored in the variable JSON. Am I missing something here?
What I have tried:
I tried storing the data in string or lists, but it was not working
推荐答案
FOR JSON
将返回单个记录,包含单个nvarchar(max)
字段,其中包含查询的JSON格式结果。
FOR JSON
will return a single record with a singlenvarchar(max)
field containing the JSON-formatted results of the query.
string json = string.Concat(entities.Database.SqlQuery("exec usp_getjsondata @type",
new SqlParameter("@type", type)
));
如果你想将它转换回对象列表,那么你需要解析JSON:
If you want to convert that back to a list of objects, then you'll need to parse the JSON:
var results = JsonConvert.DeserializeObject<IList<YourClass>>(json);
然而,如果你这样做,那么删除<$ c会更好来自查询的$ c> FOR JSON ,并将结果直接加载到列表中:
However, if you're doing that, then it would be better to remove the FOR JSON
from the query, and load the results directly into the list:
var results = entities.Database.SqlQuery<YourClass>("exec usp_getdata @type",
new SqlParameter("@type", type)
).ToList();
在SQL Server和客户端应用程序中使用FOR JSON输出(SQL服务器)| Microsoft Docs [ ^ ]
这篇关于返回控制器MVC中的json路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!