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();
}
解决方案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[^]
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[^]