json datatable

  /// <summary>
        /// 将JSON解析成DataTable,只限DataGrid标准的JSON数据
        /// 例如:Json={\"rows\":[{\"code\":\"001\",\"name\":\"Name 1\"},{\"code\":\"002\",\"name\":\"Name 2\"}]}";
        /// </summary>
        /// <param name="json">Json字符传</param>
        /// <returns>DataTable</returns>
        public static DataTable JsonToDataTable(string Json)
        {
            try
            {
                DataTable dt = new DataTable();
                JavaScriptSerializer JSS = new JavaScriptSerializer();

                object obj = JSS.DeserializeObject(Json);
                Dictionary<string, object> datajson = (Dictionary<string, object>)obj;

                //string total = datajson["total"].ToString();

                object[] rows = (object[])datajson["rows"];
                foreach (object ob in rows)
                {
                    Dictionary<string, object> val = (Dictionary<string, object>)ob;
                    DataRow dr = dt.NewRow();
                    foreach (KeyValuePair<string, object> sss in val)
                    {
                        if (!dt.Columns.Contains(sss.Key))
                        {
                            dt.Columns.Add(sss.Key.ToString());
                            dr[sss.Key] = sss.Value;
                        }
                        else
                            dr[sss.Key] = sss.Value;
                    }
                    dt.Rows.Add(dr);
                }
                return dt;
            }
            catch
            {
                return null;
            }
        }





        /// <summary>
        /// DataTable to json
        /// </summary>
        /// <param name="jsonName">返回json的名称</param>
        /// <param name="dt">转换成json的表</param>
        /// <returns>string</returns>
        public static string DataTableToJson(string jsonName, System.Data.DataTable dt)
        {
            StringBuilder Json = new StringBuilder();
            Json.Append("{\"" + jsonName + "\":[");
            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("]}");
            return Json.ToString();
        }

 

 

posted @ 2012-12-27 14:03  小川丶  阅读(306)  评论(0编辑  收藏  举报