如何使用json.net将数据表转换为jsonstring?
如何使用json.net将数据表转换为json? 任何build议…我已经下载了必要的二进制文件…我应该使用哪个类来将我的数据表转换为json? 到目前为止使用此方法通过传递我的数据表来获取jsonstring…
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<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串行器来获取jsonstring。
这和@Hasan Javaid文章类似
选中此项。
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); }