2015-02-11 53 views
4

我需要解析一些嵌在數據表中的JSON數據。 3個組中的每個組的'屬性'字段包含標題,值和優先級的內部數據。將嵌套的JSON數據解析到DataTable中

[{ 
"Title": "OVERVIEW", 
"Priority": 1, 
"attributes": [{ 
    "Title": "Type", 
    "Value": "MacBook Pro", 
    "Priority": 1 
    }, 
    { 
     "Title": "Operating system", 
     "Value": "OS X Mountain Lion", 
     "Priority": 2 
    }, 
    { 
     "Title": "Processor", 
     "Value": "Intel Core i5 Processor (2.3 GHz, 3.3 GHz with TurboBoost, 6MB cache)", 
     "Priority": 3 
    }, 
    { 
     "Title": "Storage", 
     "Value": "500 GB HDDM 5400 rpm", 
     "Priority": 4 
    }] 
}, 
{ 
"Title": "SPECIFICATION", 
"Priority": 2, 
"attributes": [{ 
    "Title": "RAM", 
    "Value": "4 GB DDR3", 
    "Priority": 1 
    }] 
}, 
{ 
"Title": "SCREEN", 
"Priority": 3, 
"attributes": [{ 
    "Title": "Screen size", 
    "Value": "13\"", 
    "Priority": 1 
    }] 
}] 

我意識到我需要先反序列化JSON數據,

List<User> UserList = JsonConvert.DeserializeObject<List<User>>(jsonString); 

public static DataTable ToDataTable<T>(this 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;   
} 

,但不知道從哪裏去那裏作爲上述只是考慮到nrmal JSON數據。任何幫助將不勝感激。

回答

2

使用此類反序列化數據

  public class TitleDesc 
    { 
     public string Title { get; set; } 
     public int Priority { get; set; } 
     public Attribute[] attributes { get; set; } 
    } 

    public class Attribute 
    { 
     public string Title { get; set; } 
     public string Value { get; set; } 
     public int Priority { get; set; } 
    } 

然後使用此代碼序列化

string jsonString = "[{'Title': 'OVERVIEW','Priority': 1,'attributes': [{ 'Title': 'Type', 'Value': 'MacBook Pro', 'Priority': 1 }, {  'Title': 'Operating system',  'Value': 'OS X Mountain Lion',  'Priority': 2 }, {  'Title': 'Processor',  'Value': 'Intel Core i5 Processor (2.3 GHz, 3.3 GHz with TurboBoost, 6MB cache)',  'Priority': 3 }, {  'Title': 'Storage',  'Value': '500 GB HDDM 5400 rpm',  'Priority': 4 }]},{'Title': 'SPECIFICATION','Priority': 2,'attributes': [{ 'Title': 'RAM', 'Value': '4 GB DDR3', 'Priority': 1 }]},{'Title': 'SCREEN','Priority': 3,'attributes': [{ 'Title': 'Screen size', 'Value': '13', 'Priority': 1 }]}]"; 
     var data = JsonConvert.DeserializeObject<TitleDesc[]>(jsonString); 

希望這有助於。

+0

是的,這是完美的!不認爲這將是直截了當的,謝謝! – Eoiner 2015-02-11 09:45:39

+0

是的,歡迎你。 – 2015-02-11 09:46:21