Created
August 8, 2016 10:47
-
-
Save kad1r/ffaff5edd4bc851a0083beaef5c84a6e to your computer and use it in GitHub Desktop.
Convert datatable to json with 2 options.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//DataTable'ı json olarak döndürmek isterseniz 2 basit yol var. Birisi JavaScriptSerializer diğeri ise Newtonsoft.Json. | |
// 1- JavaScriptSerializer | |
using System.Web.Script.Serialization; | |
public string DataTableToJsonWithJavaScriptSerializer(DataTable table) | |
{ | |
var jsSerializer = new JavaScriptSerializer(); | |
var 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); | |
} | |
//2- JsonConvert | |
using Newtonsoft.Json; | |
public string DataTableToJsonWithJsonNet(DataTable table) | |
{ | |
var jsonString=string.Empty; | |
jsonString = JsonConvert.SerializeObject(table); | |
return jsonString; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment