당신에 세 개의 열을 얻고 난 지금까지 무엇을 가지고
train_num
train_name
doj
from_station(name only)
to_station(name only)
,
public class Train
{
public string train_num { get; set; }
public string train_name { get; set; }
public string doj { get; set; }
public from_station from_station { get; set; }
public to_station to_station { get; set; }
}
public class from_station
{
public string code { get; set; }
public string name { get; set; }
}
public class to_station
{
public string code { get; set; }
public string name { get; set; }
}
public static DataTable ToDataTable(Train data)
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(Train));
DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(data);
}
table.Rows.Add(values);
return table;
}
var data = JsonConvert.DeserializeObject<Train>(JsonString);
dt = ToDataTable(data);
ui_grdVw_EmployeeDetail1.DataSource = dt;
ui_grdVw_EmployeeDetail1.DataBind();
을 표시해야 DataTable 변환을 조정해야합니다. 메소드가 Generic이 될 수 있습니다. 그런 다음 원하는대로 데이터 형식을 전달하십시오.
public static DataTable ToDataTable<T>(IList<T> data)
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
참고 : 아래의 방법은 DataTable의 모든 목록을 변환 할 수 있습니다.
사용법 :
var data = JsonConvert.DeserializeObject<Train>(JsonString);
var shapedData = Enumerable.Range(0, 1).Select(x =>
new
{
train_num = data.train_num,
train_name = data.train_name,
doj = data.doj,
from_station = data.from_station.name,
to_station = data.to_station.name
}).ToList();
DataTable dt = ToDataTable(shapedData);
왜 모든 데이터 테이블로 변환 귀찮게? 열차 객체를 직접 바인딩 할 수 있습니다. 예 : 열차 데이터 = (열차) JsonConvert.DeserializeObject (JsonString); ui_grdVw_EmployeeDetail1.DataSource = data; –
Delosdos