JSON、MODEL、DataTable、List相互转换

/// <summary>
/// DataTable 转换为 List<T>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static List<T> ToList<T>(this DataTable dt) where T : class,new()
{
    Type t = typeof(T);
    PropertyInfo[] propertys = t.GetProperties();
    List<T> lst = new List<T>();
    string typeName = string.Empty;

    foreach (DataRow dr in dt.Rows)
    {
        T entity = new T();
        foreach (PropertyInfo pi in propertys)
        {
            typeName = pi.Name;
            if (dt.Columns.Contains(typeName))
            {
                if (!pi.CanWrite) continue;
                object value = dr[typeName];
                if (value == DBNull.Value) continue;
                if (pi.PropertyType == typeof(string))
                {
                    pi.SetValue(entity, value.ToString(), null);
                }
                else if (pi.PropertyType == typeof(int) || pi.PropertyType == typeof(int?))
                {
                    pi.SetValue(entity, int.Parse(value.ToString()), null);
                }
                else if (pi.PropertyType == typeof(DateTime?) || pi.PropertyType == typeof(DateTime))
                {
                    pi.SetValue(entity, DateTime.Parse(value.ToString()), null);
                }
                else if (pi.PropertyType == typeof(float) || pi.PropertyType == typeof(float?))
                {
                    pi.SetValue(entity, float.Parse(value.ToString()), null);
                }
                else if (pi.PropertyType == typeof(double) || pi.PropertyType == typeof(double?))
                {
                    pi.SetValue(entity, double.Parse(value.ToString()), null);
                }
                else if (pi.PropertyType == typeof(byte) || pi.PropertyType == typeof(byte?))
                {
                    pi.SetValue(entity, byte.Parse(value.ToString()), null);
                }
                else if (pi.PropertyType == typeof(Int16) || pi.PropertyType == typeof(Int16?))
                {
                    pi.SetValue(entity, Int16.Parse(value.ToString()), null);
                }
                else
                {
                    pi.SetValue(entity, value, null);
                }
            }
        }
        lst.Add(entity);
    }
    return lst;
}
/// <summary>
/// 将字符串转换为Model对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="query"></param>
/// <returns></returns>
public static T StringToModel<T>(this string query)
{
    if (query.Length > 0) return JsonConvert.DeserializeObject<T>(HttpUtility.UrlDecode(query));
    else
    {
        Type type = typeof(T);
        object entity = type.Assembly.CreateInstance(type.FullName);
        return (T)entity;
    }
}
/// <summary>
/// 将MODEL转换为JSON字符串
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="model"></param>
/// <returns></returns>
public static string ModelToString<T>(this T model)
{
    return Newtonsoft.Json.JsonConvert.SerializeObject(model);
}
/// <summary>
/// 将DataRow数据行转换为JSON
/// </summary>
/// <param name="dr"></param>
/// <returns></returns>
public static string DataRowToString(this DataRow dr)
{
    DataTable dt = dr.Table.Clone();
    dt.ImportRow(dr);
    return Newtonsoft.Json.JsonConvert.SerializeObject(dt).TrimStart('[').TrimEnd(']');
}
/// <summary>
/// 表转JsonList
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string ToTableJson(this DataTable dt)
{
    StringBuilder jsonBuilder = new StringBuilder();
    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("\",");
        }
        if (dt.Columns.Count > 0) { jsonBuilder.Remove(jsonBuilder.Length - 1, 1); }
        jsonBuilder.Append("},");
    }
    if (dt.Rows.Count > 0)
    {
        jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
        jsonBuilder.Append("]");
    }
    return jsonBuilder.ToString();
}
/// <summary>
/// DataRow转Json
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string ToRowJson(this DataTable dt)
{
    StringBuilder jsonBuilder = new StringBuilder();
    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("\",");
        }
        if (dt.Columns.Count > 0) { jsonBuilder.Remove(jsonBuilder.Length - 1, 1); }
        jsonBuilder.Append("},");
    }
    if (dt.Rows.Count > 0) { jsonBuilder.Remove(jsonBuilder.Length - 1, 1); }
    return jsonBuilder.ToString();
}
/// <summary>
/// DataTable第一行转换为Model
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static T ToModel<T>(this DataTable dt)
{
    DataRow dr = dt.Rows[0];
    Type t = typeof(T);
    PropertyInfo[] propertys = t.GetProperties();
    string typeName = string.Empty;
    object entity = t.Assembly.CreateInstance(t.FullName);
    foreach (PropertyInfo pi in propertys)
    {
        typeName = pi.Name;
        if (dt.Columns.Contains(typeName))
        {
            if (!pi.CanWrite) continue;
            object value = dr[typeName];
            if (value == DBNull.Value) continue;
            if (pi.PropertyType == typeof(string))
            {
                pi.SetValue(entity, value.ToString(), null);
            }
            else if (pi.PropertyType == typeof(int) || pi.PropertyType == typeof(int?))
            {
                pi.SetValue(entity, int.Parse(value.ToString()), null);
            }
            else if (pi.PropertyType == typeof(DateTime?) || pi.PropertyType == typeof(DateTime))
            {
                pi.SetValue(entity, DateTime.Parse(value.ToString()), null);
            }
            else if (pi.PropertyType == typeof(float) || pi.PropertyType == typeof(float?))
            {
                pi.SetValue(entity, float.Parse(value.ToString()), null);
            }
            else if (pi.PropertyType == typeof(double) || pi.PropertyType == typeof(double?))
            {
                pi.SetValue(entity, double.Parse(value.ToString()), null);
            }
            else if (pi.PropertyType == typeof(byte) || pi.PropertyType == typeof(byte?))
            {
                pi.SetValue(entity, byte.Parse(value.ToString()), null);
            }
            else if (pi.PropertyType == typeof(Int16) || pi.PropertyType == typeof(Int16?))
            {
                pi.SetValue(entity, Int16.Parse(value.ToString()), null);
            }
            else
            {
                pi.SetValue(entity, value, null);
            }
        }
    }
    return (T)entity;
}
/// <summary>
/// 根据属性名称获取Model的值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="Model"></param>
/// <param name="PropertieName"></param>
/// <returns></returns>
public static object GetModelInfo<T>(this T Model, string PropertieName) where T : class,new()
{
    Type t = typeof(T);
    PropertyInfo[] propertys = t.GetProperties();
    foreach (PropertyInfo pi in Model.GetType().GetProperties())
    {
        if (pi.Name == PropertieName)
        {
            object v = pi.GetValue(Model, null);
            return v;
        }
    }
    return null;
}

 

posted @ 2019-11-11 02:33  全栈攻城师  阅读(282)  评论(0)    收藏  举报