我正在使用Angularjs,因此需要以json格式获取输出数据。我已经尝试了下面给出的Web服务来从数据库中获取数据。在这个文件服务中,我得到了xml和string的输出。我需要没有xml和字符串。
以下是代码:
[WebMethod]
public string GetDateTimeFormats()
{
DataTable dt = new DataTable();
string strQuery = null;
strQuery = "sql query";
using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection())
{
conn.ConnectionString = System.Configuration.ConfigurationManager.AppSettings["constr"];
using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand())
{
cmd.CommandText = strQuery;
cmd.Connection = conn;
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = default(Dictionary<string, object>);
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
}
}
答案 0 :(得分:0)
安装Newtonsoft.Json包。并尝试此代码。
代码
public class HelloWorldData
{
public String Message;
}
[WebMethod]
public void getEmployee()
{
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Clear();
Context.Response.ContentType = "application/json";
HelloWorldData data = new HelloWorldData();
string sql = "SQL_QUERTY";
SqlDataAdapter da = new SqlDataAdapter(sql, System.Configuration.ConfigurationManager.AppSettings["CONNECTION_STRING"]);
DataSet ds = new DataSet();
da.Fill(ds);
Context.Response.Write(JsonConvert.SerializeObject(ds, Newtonsoft.Json.Formatting.Indented));
}