DataTable
. DataTable
into a JSON object. We can accomplish the task in two simple way one is using Json.NET dll and another is by using StringBuilder class.
Using Newtonsoft Json.NET
string JSONresult;
JSONresult = JsonConvert.SerializeObject(dt);
Response.Write(JSONresult);
Reference Link: Newtonsoft: Convert DataTable to JSON object in ASP.Net C#
Using StringBuilder
public string DataTableToJsonObj(DataTable dt)
{
DataSet ds = new DataSet();
ds.Merge(dt);
StringBuilder JsonString = new StringBuilder();
if (ds != null && ds.Tables[0].Rows.Count > 0)
{
JsonString.Append("[");
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
JsonString.Append("{");
for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
{
if (j < ds.Tables[0].Columns.Count - 1)
{
JsonString.Append("\"" + ds.Tables[0].Columns[j].ColumnName.ToString() + "\":" + "\"" + ds.Tables[0].Rows[i][j].ToString() + "\",");
}
else if (j == ds.Tables[0].Columns.Count - 1)
{
JsonString.Append("\"" + ds.Tables[0].Columns[j].ColumnName.ToString() + "\":" + "\"" + ds.Tables[0].Rows[i][j].ToString() + "\"");
}
}
if (i == ds.Tables[0].Rows.Count - 1)
{
JsonString.Append("}");
}
else
{
JsonString.Append("},");
}
}
JsonString.Append("]");
return JsonString.ToString();
}
else
{
return null;
}
}
//Common DLL client, server
public class transferDataTable
{
public class myError
{
public string Message { get; set; }
public int Code { get; set; }
}
public myError Error { get; set; }
public List<string> ColumnNames { get; set; }
public List<string> DataTypes { get; set; }
public List<Object> Data { get; set; }
public int Count { get; set; }
}
public static class ExtensionMethod
{
public static transferDataTable LoadData(this transferDataTable transfer, DataTable dt)
{
if (dt != null)
{
transfer.DataTypes = new List<string>();
transfer.ColumnNames = new List<string>();
foreach (DataColumn c in dt.Columns)
{
transfer.ColumnNames.Add(c.ColumnName);
transfer.DataTypes.Add(c.DataType.ToString());
}
transfer.Data = new List<object>();
foreach (DataRow dr in dt.Rows)
{
foreach (DataColumn col in dt.Columns)
{
transfer.Data.Add(dr[col] == DBNull.Value ? null : dr[col]);
}
}
transfer.Count = dt.Rows.Count;
}
return transfer;
}
public static DataTable GetDataTable(this transferDataTable transfer, bool ConvertToLocalTime = true)
{
if (transfer.Error != null || transfer.ColumnNames == null || transfer.DataTypes == null || transfer.Data == null)
return null;
int columnsCount = transfer.ColumnNames.Count;
DataTable dt = new DataTable();
for (int i = 0; i < columnsCount; i++ )
{
Type colType = Type.GetType(transfer.DataTypes[i]);
dt.Columns.Add(new DataColumn(transfer.ColumnNames[i], colType));
}
int index = 0;
DataRow row = dt.NewRow();
foreach (object o in transfer.Data)
{
if (ConvertToLocalTime && o != null && o.GetType() == typeof(DateTime))
{
DateTime dat = Convert.ToDateTime(o);
row[index] = dat.ToLocalTime();
}
else
row[index] = o == null ? DBNull.Value : o;
index++;
if (columnsCount == index)
{
index = 0;
dt.Rows.Add(row);
row = dt.NewRow();
}
}
return dt;
}
}
//Server
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, UriTemplate = "json/data")]
transferDataTable _Data();
public transferDataTable _Data()
{
try
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["myConnString"]))
{
con.Open();
DataSet ds = new DataSet();
SqlDataAdapter myAdapter = new SqlDataAdapter("SELECT * FROM tbGalleries", con);
myAdapter.Fill(ds, "table");
DataTable dt = ds.Tables["table"];
return new transferDataTable().LoadData(dt);
}
}
catch(Exception ex)
{
return new transferDataTable() { Error = new transferDataTable.myError() { Message = ex.Message, Code = ex.HResult } };
}
}
//Client
Response = Vossa.getAPI(serviceUrl + "json/data");
transferDataTable transfer = new JavaScriptSerializer().Deserialize<transferDataTable>(Response);
if (transfer.Error == null)
{
DataTable dt = transfer.GetDataTable();
dbGrid.ItemsSource = dt.DefaultView;
}
else
MessageBox.Show(transfer.Error.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
I am using this function for describe table.
Use it after fill datatable
static public string DataTableToJSON(DataTable dataTable,bool readableformat=true)
{
string JSONString="[";
string JSONRow;
string colVal;
foreach(DataRow dataRow in dataTable.Rows)
{
if(JSONString!="[") { JSONString += ","; }
JSONRow = "";
if (readableformat) { JSONRow += "\r\n"; }
JSONRow += "{";
foreach (DataColumn col in dataTable.Columns)
{
colVal = dataRow[col].ToString();
colVal = colVal.Replace("\"", "\\\"");
colVal = colVal.Replace("'", "\\\'");
if(JSONRow!="{"&&JSONRow!="\r\n{") {
JSONRow += ",";
}
JSONRow += "\"" + col.ColumnName + "\":\"" + colVal + "\"";
}
JSONRow += "}";
JSONString += JSONRow;
}
JSONString += "\r\n]";
return JSONString;
}
MySQL Query: "DESCRIBE TableName;"; DataTableToJSON(dataTable) Example Output:
[
{"Field":"id","Type":"int(5)","Null":"NO","Key":"PRI","Default":"","Extra":"auto_increment"},
{"Field":"ad","Type":"int(11) unsigned","Null":"NO","Key":"MUL","Default":"","Extra":""},
{"Field":"soyad","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
{"Field":"ulke","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
{"Field":"alan","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
{"Field":"numara","Type":"varchar(20)","Null":"NO","Key":"","Default":"","Extra":""}
]
Tested With PHP:
$X='[
{"Field":"id","Type":"int(5)","Null":"NO","Key":"PRI","Default":"","Extra":"auto_increment"},
{"Field":"ad","Type":"int(11) unsigned","Null":"NO","Key":"MUL","Default":"","Extra":""},
{"Field":"soyad","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
{"Field":"ulke","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
{"Field":"alan","Type":"varchar(20)","Null":"YES","Key":"","Default":"","Extra":""},
{"Field":"numara","Type":"varchar(20)","Null":"NO","Key":"","Default":"","Extra":""}
]';
$Y=json_decode($X,true);
echo $Y[0]["Field"];
var_dump($Y);
This code snippet from Convert Datatable to JSON String in C#, VB.NET might help you. It uses System.Web.Script.Serialization.JavaScriptSerializer to serialize the contents to JSON format:
public string ConvertDataTabletoString()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Initial Catalog=master;Integrated Security=true"))
{
using (SqlCommand cmd = new SqlCommand("select title=City,lat=latitude,lng=longitude,description from LocationDetails", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
}
}
I have simple function to convert datatable to json string.
I have used Newtonsoft to generate string. I don't use Newtonsoft to totaly serialize Datatable. Be careful about this.
Maybe this can be useful.
private string DataTableToJson(DataTable dt) {
if (dt == null) {
return "[]";
};
if (dt.Rows.Count < 1) {
return "[]";
};
JArray array = new JArray();
foreach(DataRow dr in dt.Rows) {
JObject item = new JObject();
foreach(DataColumn col in dt.Columns) {
item.Add(col.ColumnName, dr[col.ColumnName]?.ToString());
}
array.Add(item);
}
return array.ToString(Newtonsoft.Json.Formatting.Indented);
}
public static string ConvertIntoJson(DataTable dt)
{
var jsonString = new StringBuilder();
if (dt.Rows.Count > 0)
{
jsonString.Append("[");
for (int i = 0; i < dt.Rows.Count; i++)
{
jsonString.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
jsonString.Append("\"" + dt.Columns[j].ColumnName + "\":\""
+ dt.Rows[i][j].ToString().Replace('"','\"') + (j < dt.Columns.Count - 1 ? "\"," : "\""));
jsonString.Append(i < dt.Rows.Count - 1 ? "}," : "}");
}
return jsonString.Append("]").ToString();
}
else
{
return "[]";
}
}
public static string ConvertIntoJson(DataSet ds)
{
var jsonString = new StringBuilder();
jsonString.Append("{");
for (int i = 0; i < ds.Tables.Count; i++)
{
jsonString.Append("\"" + ds.Tables[i].TableName + "\":");
jsonString.Append(ConvertIntoJson(ds.Tables[i]));
if (i < ds.Tables.Count - 1)
jsonString.Append(",");
}
jsonString.Append("}");
return jsonString.ToString();
}