加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C# 将 Json 解析成 DateTable

发布时间:2020-12-15 17:58:34 所属栏目:百科 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 #region 将 Json 解析成 DateTable /// summary /// 将 Json 解析成 DateTable。 /// Json 数据格式如: /// {table:[{column1:1,column2:2,column3:3}

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

#region 将 Json 解析成 DateTable  
        /// <summary>     
        /// 将 Json 解析成 DateTable。    
        /// Json 数据格式如:   
        ///     {table:[{column1:1,column2:2,column3:3},{column1:1,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  

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

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读