C# 將 Json 解析成 DateTable

jopen 9年前發布 | 7K 次閱讀 C# JSON

#region 將 Json 解析成 DateTable
/// <summary>
/// 將 Json 解析成 DateTable。
/// Json 數據格式如:
/// {table:[{column1:1,column2:2,column3:3},{column1:1,column2:2,column3:3}]}
/// </summary>
/// <param name="strJson">要解析的 Json 字符串</param>
/// <returns>返回 DateTable</returns>
public DataTable JsonToDataTable(string strJson)
{
// 取出表名
var rg = new Regex(@"(?<={)[^:]+(?=:[)", RegexOptions.IgnoreCase);
string strName = rg.Match(strJson).Value;
DataTable tb = null;

        // 去除表名     
        strJson = strJson.Substring(strJson.IndexOf("[") + 1);  
        strJson = strJson.Substring(0, strJson.IndexOf("]"));  

        // 獲取數據     
        rg = new Regex(@"(?<={)[^}]+(?=})");  
        MatchCollection mc = rg.Matches(strJson);  
        for (int i = 0; i < mc.Count; i++)  
        {  
            string strRow = mc[i].Value;  
            string[] strRows = strRow.Split(',');  
            // 創建表     
            if (tb == null)  
            {  
                tb = new DataTable();  
                tb.TableName = strName;  
                foreach (string str in strRows)  
                {  
                    var dc = new DataColumn();  
                    string[] strCell = str.Split(':');  
                    dc.ColumnName = strCell[0].Replace("\"", "");  
                    tb.Columns.Add(dc);  
                }  
                tb.AcceptChanges();  
            }  
            // 增加內容     
            DataRow dr = tb.NewRow();  
            for (int j = 0; j < strRows.Length; j++)  
            {  
                dr[j] = strRows[j].Split(':')[1].Replace("\"", "");  
            }  
            tb.Rows.Add(dr);  
            tb.AcceptChanges();  
        }  
        return tb;  
    }  
    #endregion  </pre> 


格式如下:

    {  
        "table": [  
            {  
                "column1": 1,   
                "column2": 2,   
                "column3": 3  
            },   
            {  
                "column1": 1,   
                "column2": 2,   
                "column3": 3  
            }  
        ]  
    }  

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!