使用JSON.NET,这非常简单。只需将您的数据表转换成等效的字典词典:
public Dictionary<string, Dictionary<string, object>> DatatableToDictionary(DataTable dt, string id){ var cols = dt.Columns.Cast<DataColumn>().Where(c => c.ColumnName != id); return dt.Rows.Cast<DataRow>() .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" }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)