如何使用json.net将datatable转换为json?任何建议......我已经下载了必要的二进制文件...我应该使用哪个类来将我的数据表转换为json? 到目前为止,使用此方法通过传递我的数据表来获取json字符串...
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();
}
现在我想过使用json.net,但不知道从哪里开始......
答案 0 :(得分:66)
string json = JsonConvert.SerializeObject(table, Formatting.Indented);
编辑:当然,你不需要缩进格式,但它使它变得美观和可读。
答案 1 :(得分:7)
也许它可以提供帮助
原始版本
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;
}
}
已修改版本
有一个中间步骤,因为我需要一本字典
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;
}
您可以添加JsonConverter.SerializeObject(result);
或其他json序列化程序来获取json字符串。
这类似于@Hasan Javaid帖子
答案 2 :(得分:0)
检查这个。
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);
}