DataTable 和 Json 互转

DataTable  To Json:


   public string DataTableToJson(System.Data.DataTable dt)
        {
            StringBuilder Json = new StringBuilder();
            Json.Append("[");
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Json.Append("{");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":\"" + dt.Rows[i][j].ToString() + "\"");
                        if (j < dt.Columns.Count - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < dt.Rows.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            //  Json.Append("]}");
            Json.Append("]");
            return Json.ToString();
        } 



Json To DataTable :


public DataTable JsonToDataTable(string strJson)
        {
            string strTableName = "Temp";
            DataTable tb = null;

            var rg = new Regex(@"(?<={)[^}]+(?=})");
            MatchCollection mc = rg.Matches(strJson);

            if(mc.Count==0)
            {
                return null;
            }
            string strRow = mc[0].Value;
            string[] strRows = strRow.Split(',');
            if (tb == null)
            {
                tb = new DataTable();
                tb.TableName = strTableName;
                foreach (string str in strRows)
                {
                    var dc = new DataColumn();
                    string[] strCell = str.Split(':');
                    dc.ColumnName = strCell[0].Replace("\"", "");
                    tb.Columns.Add(dc);
                }
                tb.AcceptChanges();
            }

            JsonArray arr = JsonConvert.Import(strJson) as JsonArray;

            foreach (JsonObject obj in arr)
            {
                DataRow dr = tb.NewRow();
                for (int j = 0; j < tb.Columns.Count; j++)
                {
                    dr[tb.Columns[j].ColumnName] = obj[tb.Columns[j].ColumnName];
                }
                tb.Rows.Add(dr);
            }

            tb.AcceptChanges();

            return tb;
        }



你可能感兴趣的:(DataTable 和 Json 互转)