如何使用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,但不知道从哪里开始....
string json = JsonConvert.SerializeObject(table, Formatting.Indented);
编辑:当然,您不需要缩进格式,但它使它变得美观和可读.
也许它会有所帮助
原始版本
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> ToDictionary(this DataTable table) { string[] columns = table.Columns.Cast ().Select(c=>c.ColumnName).ToArray(); IEnumerable > result = table.Rows.Cast () .Select(dr => columns.ToDictionary(c => c, c=> dr[c])); return result; }
您可以添加JsonConverter.SerializeObject(result);
或使用其他json序列化程序来获取json字符串.
这类似于@Hasan Javaid帖子