Convert a DataTable to JSON string
This article demonstrate how to convert a DataTable in c# to a JSON string.
The output string will be :var dt = new DataTable("MyTable"); dt.Columns.Add("ID"); dt.Columns.Add("Name"); dt.Columns.Add("Active"); dt.LoadDataRow(new[] {"ID1", "John", "True"}, true); dt.LoadDataRow(new[] {"ID2", "Bill", "False"}, true); JsonConvert.SerializeObject(DatatableToDictionary(dt, "ID"));
public Dictionary<string, Dictionary<string, object>> DatatableToDictionary(DataTable dt, string id) { var cols = dt.Columns.Cast<DataColumn>().Where(c => c.ColumnName != id); return dt.Rows.Cast<DataRow>() .ToDictionary(r => r[id].ToString(), r => cols.ToDictionary(c => c.ColumnName, c => r[c.ColumnName])); }
{
"ID1": {
"Name": "John",
"Active": "True"
},
"ID2": {
"Name": "Bill",
"Active": "False"
}
}
No comments:
Post a Comment