我是webapi的新手。我正在使用webapi中的数据表从db获取数据。我想将此数据作为json数组传递。
我该怎么做?任何帮助都很明显
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);
}
}
}
下一步做什么?
答案 0 :(得分:0)
这可以通过两种简单的方式完成,一种是使用StringBuilder类,另一种是使用Json.NET程序集 参考: Converting datatable to JsonObject
使用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);