Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
I have a stored procedure that returns a JSON path :

SQL
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:

C#
var json = entities.Database.SqlQuery("exec usp_getjsondata  @type",
               new SqlParameter("@type", type)
        ).ToList();


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
Posted
Updated 29-Aug-17 8:42am
v2

1 solution

FOR JSON will return a single record with a single nvarchar(max) field containing the JSON-formatted results of the query.
C#
string json = string.Concat(entities.Database.SqlQuery("exec usp_getjsondata  @type",
    new SqlParameter("@type", type)
));

If you want to convert that back to a list of objects, then you'll need to parse the JSON:
C#
var results = JsonConvert.DeserializeObject<IList<YourClass>>(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:
C#
var results = entities.Database.SqlQuery<YourClass>("exec usp_getdata @type",
    new SqlParameter("@type", type)
).ToList();

Use FOR JSON output in SQL Server and in client apps (SQL Server) | Microsoft Docs[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900