using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Reflection;
namespace WebApplication1
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<legal> list = new List<legal>();
string jsonstr = "[{bukrs:'2800',legalName:'张三',Icnum:'1234567890'},{bukrs:'2900',legalName:'张三1',Icnum:'12345678901'}]";
list = GetJSONToList(jsonstr);
DataTable dt=ToDataTable(list);
}
//将json字符串转成List<T>格式
public static List<legal> GetJSONToList(string jsonStr)
{
List<legal> list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<legal>>(jsonStr);
return list;
}
//跟数据库表对应的实体类
public class legal
{
//公司代码
public string bukrs { get; set; }
//姓名
public string legalName { get; set; }
//身份证号
public string Icnum { get; set; }
}
//将List<T>转成DataTable
public static DataTable ToDataTable(List<legal> collection)
{
var props = typeof(legal).GetProperties();
var dt = new DataTable();
dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray());
if (collection.Count() > 0)
{
for (int i = 0; i < collection.Count(); i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in props)
{
object obj = pi.GetValue(collection.ElementAt(i), null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
dt.LoadDataRow(array, true);
}
}
return dt;
}
}
}