在C#中将数据表转换为JSON
- 我想从数据库获取记录到
DataTable
。 - 然后将转换
DataTable
为JSON对象。 - 将JSON对象返回到我的JavaScript函数。
我通过调用以下代码来使用:
string result = JsonConvert.SerializeObject(DatatableToDictionary(queryResult, "Title"), Newtonsoft.Json.Formatting.Indented);
要将DataTable转换为JSON,它可以正常工作并返回以下内容:
{ "1": {
"viewCount": 703,
"clickCount": 98
},
"2": {
"viewCount": 509,
"clickCount": 85
},
"3": {
"viewCount": 578,
"clickCount": 86
},
"4": {
"viewCount": 737,
"clickCount": 108
},
"5": {
"viewCount": 769,
"clickCount": 130
}
}
但我希望它返回以下内容:
{"records":[{
"Title": 1,
"viewCount": 703,
"clickCount": 98
},
{
"Title": 2,
"viewCount": 509,
"clickCount": 85
},
{
"Title": 3,
"viewCount": 578,
"clickCount": 86
},
{
"Title": 4,
"viewCount": 737,
"clickCount": 108
},
{
"Title": 5,
"viewCount": 769,
"clickCount": 130
}
]}
回答:
此代码段从 C#中的“将数据表转换为JSON字符串”中,VB.NET可能会为您提供帮助。它使用System.Web.Script.Serialization.JavaScriptSerializer将内容序列化为JSON格式:
public string ConvertDataTabletoString(){
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Initial Catalog=master;Integrated Security=true"))
{
using (SqlCommand cmd = new SqlCommand("select title=City,lat=latitude,lng=longitude,description from LocationDetails", con))
{
con.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;
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);
}
}
}
以上是 在C#中将数据表转换为JSON 的全部内容, 来源链接: utcz.com/qa/424850.html