简体   繁体   English

C#DataTable到Json(具有自定义格式)

[英]C# DataTable to Json (with custom format)

I want to serialize DataTable with custom format(much smaller) - without fieldname on each row. 我想使用自定义格式(小得多)对DataTable进行序列化-每行都没有字段名。

For example, i have datatable with only 2 columns - ID and Name. 例如,我有只有2列的数据表-ID和Name。 Resulting Json should be: 结果Json应该是:

{
  "Columns": 
    [
    {"ID": "Int"},
    {"Name": "String"},
    ],
  "Rows": 
    [
    ["1","John Smith"],
    ["2","Mary Williams"]    
    ]
}

Following format will serialize even empty datatables and will not produce fieldname dublication on each row. 以下格式甚至可以序列化空的数据表,并且不会在每一行上产生字段名复制。

Any suggestion how to do it ? 有什么建议怎么办?

Here is the basics of how to do it. 这是如何做的基础。 The implementation puts everything in memory which isn't ideal for lots of data but should point you in the right direction nonetheless. 该实现将所有内容都存储在内存中,这对于大量数据而言并不理想,但是仍然可以为您指明正确的方向。 This prints the JSON you want I believe. 这会打印出您希望我相信的JSON。

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

using Newtonsoft.Json;

namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {
            var dataTable = new DataTable("test");
            dataTable.Columns.Add(new DataColumn("ID", typeof(int)));
            dataTable.Columns.Add(new DataColumn("Name", typeof(string)));

            var row1 = dataTable.NewRow();
            row1["ID"] = 1;
            row1["Name"] = "John Smith";
            dataTable.Rows.Add(row1);

            var row2 = dataTable.NewRow();
            row2["ID"] = 2;
            row2["Name"] = "Mary Williams";
            dataTable.Rows.Add(row2);

            Dictionary<string, object> result = new Dictionary<string, object> {
                ["Columns"] = dataTable.Columns.Cast<DataColumn>().Select(x => new Dictionary<string, object> { [x.ColumnName] = x.DataType.Name }).ToArray(),
                ["Rows"] = dataTable.Rows.Cast<DataRow>().Select(x => x.ItemArray).ToArray()
            };
            var json = JsonConvert.SerializeObject(result);
            Console.WriteLine($"json={json}");
        }

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM