C# 如何使用json和webapi显示数据库中的内容
我是webapi新手。我正在使用webapi中的数据表从数据库中获取数据。我想将此数据作为json数组传递 我该怎么做?任何帮助都是值得的C# 如何使用json和webapi显示数据库中的内容,c#,C#,我是webapi新手。我正在使用webapi中的数据表从数据库中获取数据。我想将此数据作为json数组传递 我该怎么做?任何帮助都是值得的 public class theatresController: ApiController { [HttpGet] public static DataTable GetAlltheatredet() { try { string connString = "Server=localhost;dat
public class theatresController: ApiController {
[HttpGet]
public static DataTable GetAlltheatredet() {
try {
string connString = "Server=localhost;database=mytable;uid=root;";
string query = "SELECT TheatName FROM `mytable`.`theatredetails`";
MySqlDataAdapter ma = new MySqlDataAdapter(query, connString);
DataSet DS = new DataSet();
ma.Fill(DS);
return DS.Tables[0];
} catch (MySqlException e) {
throw new Exception(e.Message);
}
}
}
接下来要做什么?这可以通过两种简单的方式来完成,一种是使用StringBuilder类,另一种是使用Json.NET汇编 参考: 使用Newtonsoft.json:
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=DbEmployee;Integrated Security=SSPI;");
SqlCommand cmd = new SqlCommand("Select * from tbl_EmpDetails", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
string JSONresult;
JSONresult = JsonConvert.SerializeObject(dt);
Response.Write(JSONresult);
默认情况下,
json
将传递给客户端。您使用的客户端是什么?Javascript
.Net
?您需要发出HTTP
请求才能在客户端获取它。对于javascript
或JQuery
发出ajax
.Net
客户端,使用HttpWebRequest
对象。序列化DataTable
会附带一些不必要的属性,除非否则处理。