C#中将json字符串转为DataTable,dataTable一直添加不上数据
     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;

        }
c#

3个回答

你调试下,catch里面加上异常输出,看看出什么错

if (dictionary.Keys.Count() == 0) {

Count()
这里有错,怎么弄?

新建row ,与 添加row要放到foreach循环里面

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问