C#读取DatTable返回一个嵌套的Json
Model:
public class CustomerModel { public string CLIENTID { get; set; } public DateTime DATE_C { get; set; } public bool ISACTIVE { get; set; } public string NAME { get; set; } public IList<PersonModel> ContactPersons = new List<PersonModel>(); public void Addchildren(PersonModel node) { this.ContactPersons.Add(node); } } public class PersonModel { public string CLIENTID { get; set; } public string CONTACT { get; set; } public string TEL { get; set; } public string EMAIL { get; set; } }
MainForm.cs:
public static IList<CustomerModel> customers = new List<CustomerModel>();
public List<dynamic> TableToList(DataTable dt)
{
DataTable dataTable = new DataTable();
dataTable=dt;
List<dynamic> customer = new List<dynamic>();
int rowcountall = dataTable.Rows.Count;
for (int rowcount = 0; rowcount < rowcountall; rowcount++)
{
string clientID = dataTable.Rows[rowcount][0].ToString();
NestedTree(dt, clientID);
List<dynamic> result = new List<dynamic>();
foreach (object item in customers)
{
result.Add(item);
}
customer.Add(result);
DataRow[] rows = dataTable.Select("CLIENTID='"+ clientID +"'");
foreach (DataRow row in rows)
{
dataTable.Rows.Remove(row);
}
rowcountall = dataTable.Rows.Count;
}
return customer;
}
string jsonData = JsonConvert.SerializeObject(customers);
public void NestedTree(DataTable dt, string key)
{
DataRow[] rows = dt.Select("CLIENTID='"+ key +"'");
CustomerModel customer = new CustomerModel();
customer.clientID=rows[0]["CLIENTID"].ToString();
customer.created=(DateTime)rows[0]["DATE_C"];
customer.isActive=(bool)rows[0]["ISACTIVE"];
customer.name=rows[0]["NAME_c"].ToString();
//customers.Add(customer);
List<PersonModel> contact = new List<PersonModel>();
customer.ContactPersons=contact;
foreach (DataRow row in rows)
{
PersonModel children = new PersonModel();
children.CLIENTID = row["CLIENTID"].ToString();
children.CONTACT = row["CONTACT"].ToString();
children.TEL = row["TEL"].ToString();
children.EMAIL = row["EMAIL"].ToString();
contact.Add(children);
}
customers.Add(customer);
}

浙公网安备 33010602011771号