Click here to Skip to main content
15,886,626 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Guys i have sql query which return Json string in Asp.Net C# i am unable return it please help me out of it. and i dont want to use datareader.

What I have tried:

public Employee Get()
        {
            SqlDataReader reader = null;
            SqlConnection myConnection = new SqlConnection();
            myConnection.ConnectionString = @"Data Source=Demo\SQLEXPRESS;Initial Catalog=DB;User ID=xyz;Password=xyz123;Connection Timeout=1800;";

            SqlCommand sqlCmd = new SqlCommand();
            sqlCmd.CommandType = CommandType.Text;
            string jsonOutputParam = "@jsonOutput";
            //sqlCmd.CommandText = "Create_JSON_ProjectList";
            //sqlCmd.Parameters.Add(jsonOutputParam, SqlDbType.NVarChar, -1).Direction = ParameterDirection.Output;
            sqlCmd.Connection = myConnection;
            myConnection.Open();
            string st = "select projectName from QryProjectWithDepartmentDetails ORDER BY projectName DESC FOR JSON PATH, WITHOUT_ARRAY_WRAPPER";
            //FOR JSON PATH, WITHOUT_ARRAY_WRAPPER)";
            sqlCmd = new SqlCommand(st, myConnection);
            reader = sqlCmd.ExecuteReader();
            Employee emp = null;
            while (reader.Read())
            {
                emp = new Employee();
                emp.DepartmentNmae = reader["projectName"].ToString();
               
            }
            return emp;
            myConnection.Close();  
        }
Posted
Updated 7-Dec-18 2:23am

1 solution

Your query will return one or more rows with a single string column that has an auto-generated name:
Format Query Results as JSON with FOR JSON (SQL Server) | Microsoft Docs[^]
Use FOR JSON output in SQL Server and in client apps (SQL Server) | Microsoft Docs[^]

C#
using (var myConnection = new SqlConnection("...")
using (var sqlCmd = new SqlCommand("select projectName from QryProjectWithDepartmentDetails ORDER BY projectName DESC FOR JSON PATH, WITHOUT_ARRAY_WRAPPER", myConnection))
{
    myConnection.Open();
    
    var sb = new System.Text.StringBuilder();
    using (var reader = sqlCmd.ExecuteReader())
    {
        while (reader.Read())
        {
            sb.Append(reader.GetString(0));
        }
    }
    
    return new Employee { DepartmentName = sb.ToString() };
}


NB: You should avoid hard-coding your connection strings. Read them from the config file instead:
How to: Read Connection Strings from the Web.config File | Microsoft Docs[^]
 
Share this answer
 

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