public class ModelToJson<T> where T:class{
public ClassModel GetClassModel(T t)
{
var result = new ClassModel();
var prs = typeof(T).GetProperties();
result.Name = typeof(T).Name;
//其他注解属性同理添加
var classObjs = typeof(T).GetCustomAttributes(typeof(DisplayNameAttribute), true);
result.DisplayName = classObjs.Length > 0 ? ((DisplayNameAttribute)classObjs[0]).DisplayName : typeof(T).Name;
result.Fields = new List<FieldModel>();
foreach (var pr in prs)
{
var field = new FieldModel();
var objs = pr.GetCustomAttributes(typeof(DisplayNameAttribute),true);
field.Name = pr.Name;
field.DisplayName = objs.Length > 0 ? ((DisplayNameAttribute)objs[0]).DisplayName : pr.Name;
field.Value=pr.GetValue(t,null);
result.Fields.Add(field);
}
return result;
}
public List<ClassModel> GetClassModelList(List<T> t)
{
var result = new List<ClassModel>();
foreach (var item in t)
{
result.Add(GetClassModel(item));
}
return result;
}
public string GetTable(List<T> t) {
var list = GetClassModelList(t);
var sb = new StringBuilder();
sb.Append("<link rel='stylesheet'href='https://cdn.bootcss.com/bootstrap/4.0.0/css/bootstrap.min.css'>");
sb.Append("<table class='table table-bordered'>");
{//头部添加
sb.Append("<thead>");
sb.Append("<tr>");
foreach (var item in list[0].Fields)
{
sb.Append($"<td>{item.DisplayName}</td>");
}
sb.Append("</tr>");
sb.Append("<thead>");
}
{//中间
sb.Append("<tbody>");
foreach (var item in list)
{
sb.Append("<tr>");
foreach (var field in item.Fields)
{
sb.Append($"<td>{field.Value}</td>");
}
sb.Append("</tr>");
}
sb.Append("<tbody>");
}
sb.Append("</table>");
return sb.ToString();
}
/// <summary>
/// 类描述
/// </summary>
public class ClassModel
{
public string Name { get; set; }
public string DisplayName { get; set; }
public string Table { get; set; }
public string JsonProperty { get; set; }
public List<FieldModel> Fields { get; set; }
}
/// <summary>
/// 字段描述
/// </summary>
public class FieldModel
{
public string Name { get; set; }
public string DisplayName { get; set; }
public string Column { get; set; }
public string JsonProperty { get; set; }
public object Value { get; set; }
}
}