2011-04-14 56 views
2

我想將JSON文本序列化爲DataTable,如下所示。JSON到DataTable

List<Dictionary<string, string>> list = 
JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(jsonText); 
DataTable dTable; 
dTable = (from p in list select p).CopyToDataTable(); 

我收到以下錯誤消息。我如何解決它?

錯誤:

Cannot deserialize JSON object into type 
'System.Collections.Generic.List`1[System.Collections.Generic.Dictionary`2 
[System.String,System.String]]'. 
+2

這似乎相當明顯,我認爲這無關與數據表,作爲異常被拋出在第一行。這就是你應該關注的。 – 2011-04-14 07:10:28

+0

請檢查這裏的答案 http://stackoverflow.com/a/35546685/5292650 它最簡單的一個 – 2016-02-22 06:14:27

回答

6

這個工作對我來說:

using Newtonsoft.Json; 

string json = "[{"clientID":"1788","projectID":"19"},{"clientID":"1789","projectID":"24"},{"clientID":"1790","projectID":"24"},{"clientID":"1790","projectID":"23"},{"clientID":"1790","projectID":"21"}]"; 

DataTable tester = (DataTable) JsonConvert.DeserializeObject(json, (typeof(DataTable))); 
1
public object Deserialize(string jsonText, Type valueType) 
{ 
    try 
    { 
     Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer(); 

     json.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; 
     json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace; 
     json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore; 
     json.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; 

     StringReader sr = new StringReader(jsonText); 

     Newtonsoft.Json.JsonTextReader reader = new JsonTextReader(sr); 
     object result = json.Deserialize(reader, valueType); 
     reader.Close(); 
     return result; 
    } 
    catch (Exception ex) 
    { 
     throw ex; 
    } 


} 
+0

試試這段代碼使用轉換成數據表或數據集 – 2013-01-30 09:33:49