webapi输出炜json_从WEBAPI返回json值

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[^]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值