Skip to content

Latest commit

 

History

History
54 lines (47 loc) · 1.2 KB

SerializeDataSet.md

File metadata and controls

54 lines (47 loc) · 1.2 KB

Serialize a DataSet

This sample serializes a System.Data.DataSet to JSON.

var dataSet = new DataSet("dataSet")
{
    Namespace = "NetFrameWork"
};
var table = new DataTable();
var idColumn = new DataColumn("id", typeof(int))
{
    AutoIncrement = true
};

var itemColumn = new DataColumn("item");
table.Columns.Add(idColumn);
table.Columns.Add(itemColumn);
dataSet.Tables.Add(table);

for (var i = 0; i < 2; i++)
{
    var newRow = table.NewRow();
    newRow["item"] = $"item {i}";
    table.Rows.Add(newRow);
}

dataSet.AcceptChanges();
var settings = new JsonSerializerSettings
{
    Formatting = Formatting.Indented
};

settings.AddDataSetConverters();
var json = JsonConvert.SerializeObject(dataSet, settings);

Console.WriteLine(json);
// {
//   "Table1": [
//     {
//       "id": 0,
//       "item": "item 0"
//     },
//     {
//       "id": 1,
//       "item": "item 1"
//     }
//   ]
// }

snippet source | anchor