使用每行键将DataTable转换为JSON

我认为以下是一个非常常见的任务,并假设有一个简单的解决方案,但我找不到一个。

如果我有以下结构的数据表。

ID Name Active ID1 John TRUE ID2 Bill FALSE 

我想将其序列化为JSON对象,其中ID列是JSON对象中的节点,如:

 [ { "ID1": { "Name": "John", "Active": "True" }, "ID2": { "Name": "Bill", "Active": "False" } } ] 

我查看了JSON.NET但无法使其工作。 编辑:我正在使用C#

使用JSON.NET非常简单。 只需将您的数据表转换为等效的词典字典:

 public Dictionary> DatatableToDictionary(DataTable dt, string id) { var cols = dt.Columns.Cast().Where(c => c.ColumnName != id); return dt.Rows.Cast() .ToDictionary(r => r[id].ToString(), r => cols.ToDictionary(c => c.ColumnName, c => r[c.ColumnName])); } 

然后打电话:

 JsonConvert.SerializeObject(DatatableToDictionary(dt, "ID"), Newtonsoft.Json.Formatting.Indented); 

这是完整的测试:

 var dt = new DataTable("MyTable"); dt.Columns.Add("ID"); dt.Columns.Add("Name"); dt.Columns.Add("Active"); dt.LoadDataRow(new[] {"ID1", "John", "True"}, true); dt.LoadDataRow(new[] {"ID2", "Bill", "False"}, true); JsonConvert.SerializeObject(DatatableToDictionary(dt, "ID")); 

结果如下:

 { "ID1": { "Name": "John", "Active": "True" }, "ID2": { "Name": "Bill", "Active": "False" } } 

使用JSON.NET( Newtonsoft.Json.Linq

 var obj = new JObject( dataTable.Rows.Cast() .Select(r => new JProperty(r["ID"].ToString(), new JObject( new JProperty("Name", r["Name"].ToString()), new JProperty("Active", r["Active"].ToString()) ) )) ); // Convert the JObject to a JSON string var json = obj.ToString();