这对于 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"
}
}