It seems to have found the answer, you can use System.Web.Script.Serialization;
public string DataTableToJSONWithJavaScriptSerializer(DataTable table) { JavaScriptSerializer jsSerializer = new JavaScriptSerializer(); List < Dictionary < string, object >> parentRow = new List < Dictionary < string, object >> (); Dictionary < string, object > childRow; foreach(DataRow row in table.Rows) { childRow = new Dictionary < string, object > (); foreach(DataColumn col in table.Columns) { childRow.Add(col.ColumnName, row[col]); } parentRow.Add(childRow); } return jsSerializer.Serialize(parentRow); }
Addition : If you use .Net Core, then as far as I understand you will not be able to use all the charms of System.Web.Script.Serialization; since you will not be able to connect the library System.Web.Extensions.dll. As far as I understood from this discussion in the project on Core 2.0. we cannot connect libraries from the .net framework.
Solution: humbly use the magic from the Newtonsoft.Json package;
private string DataTableToJSONWithJavaScriptSerializer(DataTable table) { try { string JSONString = string.Empty; JSONString = JsonConvert.SerializeObject(table); return JSONString; } catch (Exception ex) { Debug.WriteLine($"\n\nОшибка:\n {ex}\n\n"); } return string.Empty; }
I will be glad to your comments