DataTable
. DataTable
into a JSON object. This has similar approach to the accepted answer, but uses LINQ to convert datatable to list in a single line of code.
//convert datatable to list using LINQ. Input datatable is "dt", returning list of "name:value" tuples
var lst = dt.AsEnumerable()
.Select(r => r.Table.Columns.Cast<DataColumn>()
.Select(c => new KeyValuePair<string, object>(c.ColumnName, r[c.Ordinal])
).ToDictionary(z=>z.Key,z=>z.Value)
).ToList();
//now serialize it
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return serializer.Serialize(lst);
This is an incredibly useful way to enumerate a datatable, which would normally take a ton of coding! Here are some variations:
//convert to list with array of values for each row
var list1 = dt.AsEnumerable().Select(r => r.ItemArray.ToList()).ToList();
//convert to list of first column values only
var list2 = dt.AsEnumerable().Select(r => r.ItemArray[0]).ToList();
// parse a datatable with conditions and get CSV string
string MalesOver21 = string.Join(",",
dt.AsEnumerable()
.Where(r => r["GENDER"].ToString()=="M" && r.Field<int>("AGE")>21)
.Select(r => r.Field<string>("FULLNAME"))
);
This is off topic to the original question but for completeness sake, I'd mention that if you just want to filter out rows from an existing datatable, See this answer
Pass the datable to this method it would return json String.
public DataTable GetTable()
{
string str = "Select * from GL_V";
OracleCommand cmd = new OracleCommand(str, con);
cmd.CommandType = CommandType.Text;
DataTable Dt = OracleHelper.GetDataSet(con, cmd).Tables[0];
return Dt;
}
public string DataTableToJSONWithJSONNet(DataTable table)
{
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(table);
return JSONString;
}
public static DataSet GetDataSet(OracleConnection con, OracleCommand cmd)
{
// create the data set
DataSet ds = new DataSet();
try
{
//checking current connection state is open
if (con.State != ConnectionState.Open)
con.Open();
// create a data adapter to use with the data set
OracleDataAdapter da = new OracleDataAdapter(cmd);
// fill the data set
da.Fill(ds);
}
catch (Exception ex)
{
throw;
}
return ds;
}
With Cinchoo ETL - an open source library, you can export DataTable to JSON easily with few lines of code
StringBuilder sb = new StringBuilder();
string connectionstring = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Northwind;Integrated Security=True";
using (var conn = new SqlConnection(connectionstring))
{
conn.Open();
var comm = new SqlCommand("SELECT * FROM Customers", conn);
SqlDataAdapter adap = new SqlDataAdapter(comm);
DataTable dt = new DataTable("Customer");
adap.Fill(dt);
using (var parser = new ChoJSONWriter(sb))
parser.Write(dt);
}
Console.WriteLine(sb.ToString());
Output:
{
"Customer": [
{
"CustomerID": "ALFKI",
"CompanyName": "Alfreds Futterkiste",
"ContactName": "Maria Anders",
"ContactTitle": "Sales Representative",
"Address": "Obere Str. 57",
"City": "Berlin",
"Region": null,
"PostalCode": "12209",
"Country": "Germany",
"Phone": "030-0074321",
"Fax": "030-0076545"
},
{
"CustomerID": "ANATR",
"CompanyName": "Ana Trujillo Emparedados y helados",
"ContactName": "Ana Trujillo",
"ContactTitle": "Owner",
"Address": "Avda. de la Constitución 2222",
"City": "México D.F.",
"Region": null,
"PostalCode": "05021",
"Country": "Mexico",
"Phone": "(5) 555-4729",
"Fax": "(5) 555-3745"
}
]
}
You can use the same way as specified by Alireza Maddah and if u want to use two data table into one json array following is the way:
public string ConvertDataTabletoString()
{
DataTable dt = new DataTable();
DataTable dt1 = 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);
}
SqlCommand cmd1 = new SqlCommand("_another_query_", con);
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
da1.Fill(dt1);
System.Web.Script.Serialization.JavaScriptSerializer serializer1 = new System.Web.Script.Serialization.JavaScriptSerializer();
Dictionary<string, object> row1;
foreach (DataRow dr in dt1.Rows) //use the old variable rows only
{
row1 = new Dictionary<string, object>();
foreach (DataColumn col in dt1.Columns)
{
row1.Add(col.ColumnName, dr[col]);
}
rows.Add(row1); // Finally You can add into old json array in this way
}
return serializer.Serialize(rows);
}
}
}
The same way can be used for as many as data tables as you want.
try this (ExtensionMethods):
public static string ToJson(this DataTable dt)
{
List<Dictionary<string, object>> lst = new List<Dictionary<string, object>>();
Dictionary<string, object> item;
foreach (DataRow row in dt.Rows)
{
item = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
item.Add(col.ColumnName, (Convert.IsDBNull(row[col]) ? null : row[col]));
}
lst.Add(item);
}
return Newtonsoft.Json.JsonConvert.SerializeObject(lst);
}
and use:
DataTable dt = new DataTable();
.
.
.
var json = dt.ToJson();