使用Newtonsoft.Json经常会碰到一些莫名奇妙的问题,比方说它有时候没有办法把DataTable.Rows[0]转换成一个Model对象,下面我们提供一段代码来解决这个问题:
技术要点:使用了反射
转换方法,使用实例:
var Model = new MyModel();
var dt = SqlHelper.GetDt("");
Model = TableRowToModel(Model,Dt.Rows[0]);
//这是具体方法
public static T TableRowToModel<T>(T objmodel, DataRow dtRow)
{
foreach (PropertyInfo info in typeof(T).GetProperties())
{
string name = info.Name;
if (dtRow.Table.Columns.Contains(name))
{
if (!info.PropertyType.IsGenericType)
{
info.SetValue(objmodel, string.IsNullOrEmpty(dtRow[name].ToString()) ? null : Convert.ChangeType(dtRow[name], info.PropertyType), null);
}
else if (info.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
info.SetValue(objmodel, string.IsNullOrEmpty(dtRow[name].ToString()) ? null : Convert.ChangeType(dtRow[name], Nullable.GetUnderlyingType(info.PropertyType)), null);
}
}
}
return objmodel;
}