public class ConvertHelper<T>where T:new()
{
/// <summary>
/// 利用反射和泛型
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static List<T> ConvertToList(DataTable dt)
{
// 定義集合
List<T> ts = new List<T>();
// 獲得此模型的類型
Type type = typeof(T);
//定義一個臨時變量
string tempName = string.Empty;
//遍歷DataTable中所有的數據行
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)
{
if (pi.PropertyType.Name == "Guid")
pi.SetValue(t, Guid.Parse(value.ToString()), null);
else if (pi.PropertyType.Name == "string" || pi.PropertyType.Name == "String")
{
pi.SetValue(t, value.ToString(), null);
}
else
pi.SetValue(t, value, null);
}
}
}
//對象添加到泛型集合中
ts.Add(t);
}
return ts;
}
}
public class DT2Json
{
public static string DataTable2Json(DataTable dt)
{
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.Append("{\"");
jsonBuilder.Append(dt.TableName);
jsonBuilder.Append("\":[");
for (int i = 0; i < dt.Rows.Count; i++)
{
jsonBuilder.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
jsonBuilder.Append("\"");
jsonBuilder.Append(dt.Columns[j].ColumnName);
jsonBuilder.Append("\":\"");
jsonBuilder.Append(dt.Rows[i][j].ToString());
jsonBuilder.Append("\",");
}
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("},");
}
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("]");
jsonBuilder.Append("}");
return jsonBuilder.ToString();
}
}