如何遍历嵌套的Dictionary <string,object =“”>?

时间:2016-08-23 12:28:55

标签: c# json

我有一个JSON文件,我需要使用类System.Web.Script.Serialization反序列化。以下代码:

string json = File.ReadAllText(@"C:\file.json");
JavaScriptSerializer ser = new JavaScriptSerializer();
var dict = ser.Deserialize<Dictionary<string, object>>(json);

创建一个嵌套字典,如下所示:

Dictionary<string, Object> outerDictionary;
Dictionary<string, Object> middleDictionary;
Dictionary<string, string> innerDictionary;

我现在需要从innerDictionary中获取一些值到C#对象类中,如:

public class Location
{
   public string Id { get; set; }
   public string Name { get; set; }
   public string Street { get; set; }
   public string City { get; set; }
   public string State { get; set; }
   public string Zip { get; set; }
}

所以我的问题是,如何迭代嵌套的disctionary以获得我最需要的值?

更新

Jonesopolis的帮助下,我现在有了正确的循环结构,但是我仍然无法从最里面的字典中获取值?

foreach (var outer in dict)
{
    foreach (var middle in (Dictionary<string, object>)outer.Value)
    {
        foreach (var inner in (ArrayList)middle.Value)
        {
            foreach (var loc in (Dictionary<string, object>)inner)
            {
            }
         }
    }
}

2 个答案:

答案 0 :(得分:1)

如果您不喜欢Jonesopolis's answer中的嵌套foreach,那么您可以这样使用LINQ:

var data = from outer in dict
           from middle in (Dictionary<string, object>) outer.Value
           from inner in (Dictionary<string, string>) middle.Value
           select new { outer, middle, inner };

foreach (var item in data) {
    // do things with item.inner
}

答案 1 :(得分:0)

如果您真的想使用这些对象:

foreach(var outer in dict)
{
    foreach (var middle in (Dictionary<string, object>) outer.Value)
    {
         foreach (var inner in (Dictionary<string, string>) middle.Value)
         {
              var location = new Location();
              location.Id = inner["Id"]; 
              //etc..
         }      
    }
}
但是,创建一个可以反序列化json的类结构会更好,它可以准确地表示你的数据,而不是生成字典。