2012-07-05 115 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)); 
相关问题