表单字典<字符串、字典<字符串、字符串的 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但出现错误:

无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型"System.Collections.Generic.Dictionary'2[System.String,System.Collections.Generic.Dictionary'2[System.String,System.String]]",因为该类型需要 JSON 对象(例如 {"name":"value"})才能正确反序列化。要修复此错误,请将 JSON 更改为 JSON 对象(例如 {"name":"value"}),或者将反序列化类型更改为数组或实现集合接口的类型(例如 ICollection、IList),如可以从 JSON 数组反序列化的列表。还可以将 JsonArrayAttribute 添加到类型中,以强制它从 JSON 数组反序列化。路径 '',第 1 行,位置 1。

还有其他方法可以做到这一点吗?

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

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));

最新更新