- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Data;
- using System.Collections;
- using System.Reflection;
- namespace DatableToList
- {
- 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)
- pi.SetValue(t, value, null);
- }
- }
- //對象添加到泛型集合中
- ts.Add(t);
- }
- return ts;
- }
- }
- }
/// <summary>
/// 將集合類轉換成DataTable
/// </summary>
/// <param name="list">集合</param>
/// <returns></returns>
public static DataTable ToDataTable(IList list)
{
DataTable result = new DataTable();
if (list.Count > 0)
{
PropertyInfo[] propertys = list[0].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
result.Columns.Add(pi.Name, pi.PropertyType);
}
for (int i = 0; i < list.Count; i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
result.LoadDataRow(array, true);
}
}
return result;
}
/// <summary>
/// 將泛型集合類轉換成DataTable
/// </summary>
/// <typeparam name="T">集合項類型</typeparam>
/// <param name="list">集合</param>
/// <returns>數據集(表)</returns>
public static DataTable ToDataTable<T>(IList<T> list)
{
return ConvertX.ToDataTable<T>(list, null);
}
/// <summary>
/// 將泛型集合類轉換成DataTable
/// </summary>
/// <typeparam name="T">集合項類型</typeparam>
/// <param name="list">集合</param>
/// <param name="propertyName">需要返回的列的列名</param>
/// <returns>數據集(表)</returns>
public static DataTable ToDataTable<T>(IList<T> list, params string[] propertyName)
{
List<string> propertyNameList = new List<string>();
if (propertyName != null)
propertyNameList.AddRange(propertyName);
DataTable result = new DataTable();
if (list.Count > 0)
{
PropertyInfo[] propertys = list[0].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
if (propertyNameList.Count == 0)
{
result.Columns.Add(pi.Name, pi.PropertyType);
}
else
{
if (propertyNameList.Contains(pi.Name))
result.Columns.Add(pi.Name, pi.PropertyType);
}
}
for (int i = 0; i < list.Count; i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
if (propertyNameList.Count == 0)
{
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
else
{
if (propertyNameList.Contains(pi.Name))
{
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
}
}
object[] array = tempList.ToArray();
result.LoadDataRow(array, true);
}
}
return result;
}
List<T>轉Json
public static string Obj2Json<T>(T data)
{
try
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(data.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, data);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
catch
{
return null;
}
}
Json轉List<T>
public static Object Json2Obj(String json,Type t)
{
try
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(t);
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
return serializer.ReadObject(ms);
}
}
catch
{
return null;
}
}
DataTable 轉Json
public static string DataTable2Json(DataTable dt)
{
if (dt.Rows.Count == 0)
{
return "";
}
StringBuilder jsonBuilder = new StringBuilder();
// jsonBuilder.Append("{");
//jsonBuilder.Append(dt.TableName.ToString());
jsonBuilder.Append("[");//轉換成多個model的形式
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();
}
單個對象轉JSON
public static T Json2Obj<T>(string json)
{
T obj = Activator.CreateInstance<T>();
using (System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(json)))
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
return (T)serializer.ReadObject(ms);
}
}