oiu1010110
白日梦想jun
2017-08-14 12:58

C#中将json字符串转为DataTable,dataTable一直添加不上数据

  • c#
     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;

        }
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

3条回答

为你推荐

换一换