白日梦想jun 2017-08-14 12:58 采纳率: 100%
浏览 2206

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;

        }
  • 写回答

3条回答

  • threenewbee 2017-08-14 16:22
    关注

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

    评论

报告相同问题?

悬赏问题

  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题