1. 我想把数据库里的记录加到DataTable.
  2. Then convert the DataTable into a JSON object.
  3. 将JSON对象返回给我的JavaScript函数.

我用this码打电话:

string result = JsonConvert.SerializeObject(DatatableToDictionary(queryResult, "Title"), Newtonsoft.Json.Formatting.Indented);

To convert a DataTable to JSON, it works correctly and return the following:

{
    "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
}
]} 

How can I do this?

推荐答案

This code snippet from Convert Datatable to JSON String in C#, VB.NET might help you. It uses System.Web.Script.Serialization.JavaScriptSerializer to serialize the contents to JSON format:

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);
        }
    }
}

Json相关问答推荐

JOLT转换,将属性复制到同级别的dict中

如何在Power BI中集成API和JSON数据后将数据转换为表?

删除JSON文件的特定内容

使用动态和可变JSON的图表多条

如何在PowerShell中访问嵌套的JSON字段

重构JOLT代码以获得预期输出

Jolt-Json转换:通过引用标识符(而不是索引)设置值

使用 jq 获取所有嵌套键和值

使用 serde 和 csv crates 将嵌套的 json 对象序列化为 csv

如何将 JSON 文本作为参数传递给 powershell?

Jolt 变换 - 如何用字段值重命名字段?

嵌套存储在字符串变量中的 JSON 对象

Powershell JSON 操作

Angular 2/Web Api - json 解析错误语法错误意外结束输入

如何将任意 json 对象发布到 webapi

ASP.NET MVC:使用 JsonResult 控制属性名称的序列化

使用 GSON 解析嵌套的 JSON 数据

没有默认构造函数的杰克逊第 3 方类

在 React 中访问子级的父级状态

Java HashMap 与 JSONObject