C# json字符串转DataTable

我的json格式是这样的:

{"success":true,"data":[{"C4":"英语","C3":"","C1":"99","C2":"CCC"},{"C4":"数学","C3":"","C1":"55","C2":"DDD"}]}

转出来的结果:

C# json字符串转DataTable

 

代码:

1. 需要引用 Newtonsoft.Json.dll , 可以去网上下载

2.引入System.Web.Extensions 组件

引用  :

using System.Text.RegularExpressions;
using System.Web.Script.Serialization;

 

3.

public  DataTable   JsonToDataTable(string strJson)
        {
             DataTable dt =null ;
            try
            {
                JObject jo = (JObject)JsonConvert.DeserializeObject(strJson);
                bool success = (bool)jo["success"];
                if (!success)
                {
                    return null;
                }
                JArray ja = (JArray)jo["data"];
                dt = ToDataTable(ja.ToString());
            }
            catch (Exception ex)
            {
                return null;
            }
            return dt;
        }

方法ToDataTable

public  DataTable ToDataTable( string json)  
        {
            DataTable dataTable = new DataTable();  //实例化
            DataTable result;
            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)
                    if (dictionary.Keys.Count == 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);
                }
            }
            result = dataTable;
            return result;
        }

 

C# json字符串转DataTable

上一篇:记一次局部变量操作


下一篇:C#读取csv格式文件