码迷,mamicode.com
首页 > Windows程序 > 详细

C# json字符串转DataTable

时间:2014-10-30 14:54:35      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   io   color   os   ar   java   

我的json格式是这样的:

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

转出来的结果:

bubuko.com,布布扣

 

代码:

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

标签:des   style   blog   http   io   color   os   ar   java   

原文地址:http://www.cnblogs.com/Marvellous/p/4062465.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!