0

I want to serialize DataTable with custom format(much smaller) - without fieldname on each row.

For example, i have datatable with only 2 columns - ID and Name. Resulting Json should be:

{
  "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 ?

1

1 Answer 1

1

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.

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

    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I've edited to add the type in the columns. Hope that works for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.