2012-07-05 139 views
3

我想反序列化一個形式爲[{"key" : "Microsoft", "value":[{"Key":"Publisher","Value":"abc"},{"Key":"UninstallString","Value":"c:\temp"}]} and so on ]的json字符串到C#對象。Json反序列化形式Dictionary <string,Dictionary <string,string >>

它基本上是Dicionary<string, Dictionary<string, string>>的形式。我嘗試使用Newtonsoft的JsonConvert.Deserialize但得到了一個錯誤:

 
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.Dictionary`2[System.String,System.String]]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. 

To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. 
Path '', line 1, position 1. 

是否有其他替代辦法做到這一點?

+1

只需使用'VAR OBJ = JsonConvert.DeserializeObject(...)'。它適用於你的json字符串 – 2012-07-05 22:34:38

+0

即時做這個目前...字符串jsonString = json; (這包含上述格式的json) var values = JsonConvert.DeserializeObject >>(jsonString); ........我仍然得到相同的錯誤。 – barry 2012-07-05 22:39:09

+0

'我現在正在做這個.'你爲什麼不嘗試我發佈的代碼?我測試了它,它工作。 – 2012-07-05 22:43:11

回答

5

我能找到的最好的辦法是:

string json = @"[{""Key"" : ""Microsoft"", ""Value"":[{""Key"":""Publisher"",""Value"":""abc""},{""Key"":""UninstallString"",""Value"":""c:\temp""}]}]"; 

var list = JsonConvert.DeserializeObject< List<KeyValuePair<string,List<KeyValuePair<string, string>>>> >(json); 

var dict= list.ToDictionary(
     x => x.Key, 
     x => x.Value.ToDictionary(y=>y.Key,y=>y.Value)); 
相關問題