How to convert datatable to json using json.net? Any suggestion... I ve downloaded the necessary binaries... Which class should i use to get the conversion of my datatable to json? Thus far used this method to get json string by passing my datatable...
public string GetJSONString(DataTable table)
{
StringBuilder headStrBuilder = new StringBuilder(table.Columns.Count * 5); //pre-allocate some space, default is 16 bytes
for (int i = 0; i < table.Columns.Count; i++)
{
headStrBuilder.AppendFormat("\"{0}\" : \"{0}{1}¾\",", table.Columns[i].Caption, i);
}
headStrBuilder.Remove(headStrBuilder.Length - 1, 1); // trim away last ,
StringBuilder sb = new StringBuilder(table.Rows.Count * 5); //pre-allocate some space
sb.Append("{\"");
sb.Append(table.TableName);
sb.Append("\" : [");
for (int i = 0; i < table.Rows.Count; i++)
{
string tempStr = headStrBuilder开发者_如何学编程.ToString();
sb.Append("{");
for (int j = 0; j < table.Columns.Count; j++)
{
table.Rows[i][j] = table.Rows[i][j].ToString().Replace("'", "");
tempStr = tempStr.Replace(table.Columns[j] + j.ToString() + "¾", table.Rows[i][j].ToString());
}
sb.Append(tempStr + "},");
}
sb.Remove(sb.Length - 1, 1); // trim last ,
sb.Append("]}");
return sb.ToString();
}
Now i thought of using json.net but dont know where to get started....
string json = JsonConvert.SerializeObject(table, Formatting.Indented);
Edit: You don't need indented formatting, of course, but it makes it nice and readable.
Maybe it could help
Original version
public static class DataTableToJson
{
public static JArray ToJson(this System.Data.DataTable source)
{
JArray result = new JArray();
JObject row;
foreach (System.Data.DataRow dr in source.Rows)
{
row = new JObject();
foreach (System.Data.DataColumn col in source.Columns)
{
row.Add(col.ColumnName.Trim(), JToken.FromObject(dr[col]));
}
result.Add(row);
}
return result;
}
}
Edited Version
There is a intermediate step because I needed to have a dictionary
public static IEnumerable<Dictionary<string, object>> ToDictionary(this DataTable table)
{
string[] columns = table.Columns.Cast<DataColumn>().Select(c=>c.ColumnName).ToArray();
IEnumerable<Dictionary<string, object>> result = table.Rows.Cast<DataRow>()
.Select(dr => columns.ToDictionary(c => c, c=> dr[c]));
return result;
}
You can add JsonConverter.SerializeObject(result);
, or another json serializer to get json string.
This is similar to @Hasan Javaid post
Check this.
private static string DataTableToJson(DataTable dataTable)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
var rows = (from DataRow d in dataTable.Rows
select dataTable.Columns.Cast<DataColumn>().ToDictionary(col => col.ColumnName, col => d[col])).ToList();
rows.AddRange(from DataRow d in dataTable.Rows
select dataTable.Columns.Cast<DataColumn>().ToDictionary(col => col.ColumnName, col => d[col]));
return serializer.Serialize(rows);
}
精彩评论