json = "[{\"id\":\"329\",\"txt\":\"IT\"}, {\"id\":\"338\",\"txt\":\"机构2\"},{\"id\":\"888\",\"txt\":\"内部2\"}]";
DataTable dt = jsonToDataTable(json);
public static DataTable jsonToDataTable(string json){
DataTable dataTable = new DataTable();
DataTable result = null;
try
{
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
javaScriptSerializer.MaxJsonLength = Int32.MaxValue;
ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(json);
if (arrayList.Count > 0) {
foreach (Dictionary<string, object> dictionary in arrayList) {
if (dictionary.Keys.Count<string>() == 0) {
result = dataTable;
return result;
}
if (dataTable.Columns.Count == 0) {
foreach (string current in dictionary.Keys) {
dataTable.Columns.Add(current,dictionary[current].GetType());
}
}
DataRow dataRow = dataTable.NewRow();
foreach (string current in dictionary.Keys) {
dataRow[current] = dictionary[current];
}
dataTable.Rows.Add(dataRow); //这里dataRow都有值,但是dataTable一直是空的
}
}
}
catch { };
result = dataTable;
return result;
}
你调试下,catch里面加上异常输出,看看出什么错
新建row ,与 添加row要放到foreach循环里面
if (dictionary.Keys.Count() == 0) {
Count()
这里有错,怎么弄?