2016-07-21 21 views
1

我需要將以下JSON字符串轉換爲數據表。嵌套的JSON字符串到數據表

{ 
    "pnr":"1234567890", 
    "train_num":"12311", 
    "train_name":"HWH DLIKLK MAI", 
    "doj":"23-12-2013", 
    "from_station": 
    { 
     "code":"DLI", 
     "name":"Delhi" 
    }, 
    "to_station": 
    { 
     "code":"KLK", 
     "name":"Kalka" 
    } 
} 

DataTable中我需要顯示

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(); 

我只得到了三列數據表

train_num 
train_name 
doj 
+0

爲什麼還要轉換成一個數據表呢?你可以直接綁定你的火車對象。例如列車數據=(列車)JsonConvert.DeserializeObject (JsonString); ui_grdVw_EmployeeDetail1.DataSource = data; – Delosdos

回答

3

你需要調整你的DataTable轉換方法更通用。然後傳遞給你想要的數據。

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; 
} 

注:下面的方法可以用於任何列表轉換爲數據表。

用法:

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); 
+0

它的工作。非常感謝 – Soniya

+0

如果是相反方向呢?你應該如何將數據表格格式化爲嵌套JSON? –

相關問題