将json字符串转换为DataTable

Posted soulbky

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将json字符串转换为DataTable相关的知识,希望对你有一定的参考价值。

字符串

 {

"Answer": [{
        "PatientId": "xx",
        "Question": "158",
        "AnswerContent": "3"
    }, {
        "PatientId": "aa",
        "Question": "159",
        "AnswerContent": "2"
    }]

}

 

 

 public DataTable JsonTdb(string strJson)
        {
            DataTable dataTable = new DataTable();  //实例化
            DataTable result;
             try
                {
                    
                    javascriptSerializer javaScriptSerializer = new JavaScriptSerializer();    //引用System.Web.Extensions
                    javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
                    ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(strJson);
                    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); //循环添加行到DataTable中
                        }
                    }
                }
                catch
                {
                }
              return   dataTable;
                // return result;
            }


















































以上是关于将json字符串转换为DataTable的主要内容,如果未能解决你的问题,请参考以下文章

将json字符串转换为DataTable

DataTable 对象 转换为Json 字符串

在.Net Core 3.1中使用NewtonSoft将DataTable转换为JSON字符串时如何使JSON字符串不包含'\u0022'或'\'等字符[重复]

C#将datatable的某一列转换成json格式的字符串

Datatable转换为Json

c#常用的Datable转换为json,以及json转换为DataTable操作方法