0

I want to serialize a DataTable object which has no rows, but it has columns.

Now Newtonsoft JSON.NET serializes such a DataTable as a totally empty table, without columns.

However, I want the names and the types of the columns!

How can I configure JSON.NET to serialize an empty DataTable with Column Names and Column Types ?

askolotl
  • 964
  • 1
  • 13
  • 27

1 Answers1

1

Assuming you have a DataTable dt then you can project the columns into a list of anonymous type (containing ColumnName and Type) using Linq like this:

var columns = dt.Columns
                .Cast<DataColumn>()
                .Select(c => new { Name = c.ColumnName, Type = c.DataType.ToString()});

Then using Newtonsoft.Json you can serialize like this:

var json = JsonConvert.Serialize(columns);

Or using System.Text.Json:

var json = JsonSerializer.Serialize(columns);

Which (if your table has 3 columns - Id, Name, Date) will produce JSON something like this:

[
  {
    "Name": "Id",
    "Type": "System.Int32"
  },
  {
    "Name": "Name",
    "Type": "System.String"
  },
  {
    "Name": "Date",
    "Type": "System.DateTime"
  }
]
haldo
  • 14,512
  • 5
  • 46
  • 52
  • This is a great idea, so actually the columns are serialized as a separate list. This might also solve another issue, as all Int32 are converted to Int64 during serialization and de-serialization. I will try it and come back later here. – askolotl Nov 07 '19 at 12:33