首页 > 技术文章 > 将JSON(List集合)转成DataSet(DataTable)

elves 2014-03-17 09:55 原文

方法1:

 /// <summary>
        /// 将JSON解析成DataSet只限标准的JSON数据
        /// 例如:Json={t1:[{name:'数据name',type:'数据type'}]} 
        /// 或 Json={t1:[{name:'数据name',type:'数据type'}],t2:[{id:'数据id',gx:'数据gx',val:'数据val'}]}
        /// </summary>
        /// <param name="Json">Json字符串</param>
        /// <returns>DataSet</returns>
        public static DataSet JsonToDataSet(string Json)
        {
            try
            {
                DataSet ds = new DataSet();
                JavaScriptSerializer JSS = new JavaScriptSerializer();


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


                foreach (var item in datajson)
                {
                    DataTable dt = new DataTable(item.Key);
                    object[] rows = (object[])item.Value;
                    foreach (var row in rows)
                    {
                        Dictionary<string, object> val = (Dictionary<string, object>)row;
                        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);
                    }
                    ds.Tables.Add(dt);
                }
                return ds;
            }
            catch
            {
                return null;
            }
        }

方法2:

        /// <summary>   
        /// 根据Json返回DateTable,JSON数据格式如:   
        /// {table:[{column1:1,column2:2,column3:3},{column1:1,column2:2,column3:3}]}   
        /// items:{"2750884":{clicknum:"50",title:"鲍鱼",href:"/shop/E06B14B40110/dish/2750884#menu",desc:"<br/>",src:"15f38721-49da-48f0-a283-8057c621b472.jpg",price:78.00,units:"",list:[],joiner:""}}
        /// </summary>   
        /// <param name="strJson">Json字符串</param>   
        /// <returns></returns>   
        public static DataTable JsonToDataTable(string strJson)
        {
            //取出表名   
            //var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase);
            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(@"(?<={)[^}]+(?=})");
            rg = new Regex(@"(?<={)[^}]+(?=})");

            System.Text.RegularExpressions.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];
                        tb.Columns.Add(dc);
                    }
                    tb.AcceptChanges();
                }

                //增加内容   
                DataRow dr = tb.NewRow();
                for (int r = 0; r < strRows.Length; r++)
                {
                    //dr[r] = strRows[r].Split(':')[1].Trim().Replace(",", ",").Replace(":", ":").Replace("\"", "");
                    dr[r] = strRows[r];
                }
                tb.Rows.Add(dr);
                tb.AcceptChanges();
            }

            return tb;
        }

 

    /// <summary>
    /// List转DataTable
    /// </summary>
        public static DataTable ListToDataTable<T>(IEnumerable<T> collection)
        {
            var tb = new DataTable(typeof(T).Name);
            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo prop in props)
            {
                Type t = GetCoreType(prop.PropertyType);
                tb.Columns.Add(prop.Name, t);
            }
            foreach (T item in collection)
            {
                var values = new object[props.Length];

                for (int i = 0; i < props.Length; i++)
                {
                    values[i] = props[i].GetValue(item, null);
                }

                tb.Rows.Add(values);
            }

            return tb;
        }
           /// <summary>
           /// Determine of specified type is nullable
           /// </summary>
           public static bool IsNullable(Type t)
           {
               return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
           }
   
           /// <summary>
           /// Return underlying type if type is Nullable otherwise return the type
           /// </summary>
           public static Type GetCoreType(Type t)
           {
               if (t != null && IsNullable(t))
               {
                   if (!t.IsValueType)
                   {
                       return t;
                   }
                   else
                   {
                       return Nullable.GetUnderlyingType(t);
                   }
               }
               else
               {
                   return t;
               }
           }    

 

/// <summary>
/// List转DataTable
/// </summary>
public static DataTable ListToDataTable<T>(List<T> list)
{
    if(list==null || list.Count==0)
    {
        return new DataTable();
    }
    //获取T下所有的属性
    Type entityType = list[0].GetType();
    PropertyInfo[] entityProperties = entityType.GetProperties();

    DataTable dt = new DataTable("data");
    for(int i=0; i<entityProperties.Length; i++)
    {
        dt.Columns.Add(entityProperties[i].Name);
    }
    foreach (var item in list)
    {
        if(item.GetType() != entityType)
        {
            throw new Exception("要转换集合元素类型不一致!")
        }
        //创建一个用于放所有属性值的数组
        object[] entityValues = new object[entityProperties.Length];
        for(int i=0; i<entityProperties.Length; i++)
        {
            entityValues[i] = entityProperties[i].GetValue(item, null);
        }
        
        dt.Rows.Add(entityValues)
    }
    return dt;
}

/// <summary>
/// DataTable转List
/// </summary>
public static IList<T> ConvertToModel(DataTable dt)    
{    
   // 定义集合    
    IList<T> ts = new List<T>(); 
   // 获得此模型的类型   
    Type type = typeof(T);      
   string tempName = "";      
   foreach (DataRow dr in dt.Rows)      
    {    
        T t = new T();     
       // 获得此模型的公共属性      
        PropertyInfo[] propertys = t.GetType().GetProperties(); 
       foreach (PropertyInfo pi in propertys)      
        {      
            tempName = pi.Name;  // 检查DataTable是否包含此列   
           if (dt.Columns.Contains(tempName))      
            {      
               // 判断此属性是否有Setter      
               if (!pi.CanWrite) continue;        
               object value = dr[tempName];      
               if (value != DBNull.Value)      
                    pi.SetValue(t, value, null);  
            }     
        }      
        ts.Add(t);      
    }     
   return ts;     
}

 

推荐阅读