一尘不染

在C#中将数据表转换为JSON

c#

  1. 我想从数据库获取记录到DataTable
  2. 然后将转换DataTable为JSON对象。
  3. 将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
}
]}

我怎样才能做到这一点?


阅读 696

收藏
2020-05-19

共1个答案

一尘不染

此代码段从 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);
        }
    }
}
2020-05-19