Json反序列化形式Dictionary <string,dictionary <string,=“”string =“”>&gt; </string,>

时间:2012-07-05 22:27:52

标签: c# json

我正在尝试将形式为[{"key" : "Microsoft", "value":[{"Key":"Publisher","Value":"abc"},{"Key":"UninstallString","Value":"c:\temp"}]} and so on ]的json字符串反序列化为C#对象。

它基本上采用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 个答案:

答案 0 :(得分: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));