c#中的多级字典错误

时间:2013-07-17 12:34:23

标签: c# json dictionary keynotfoundexception

我使用以下代码制作JSON

        FilterModel f = new FilterModel();
        f.FilterName = "EducationLevel";
        f.filterValue = new List<string>();
        f.filterValue.Add("BE");
        f.GroupName="Education";


        FilterDictionary d = new FilterDictionary();
        d.FilterValuse = new Dictionary<string, List<string>>();
        d.FilterValuse.Add(f.FilterName, f.filterValue);

        FilterSelectModel ff = new FilterSelectModel();

        ff.Filters = new Dictionary<string, Dictionary<string, List<string>>>();

        ff.Filters[f.GroupName].Add(f.FilterName, f.filterValue);



        var json = new JavaScriptSerializer().Serialize(ff);
        Response.Write(json);

但它在下面的行中显示了一个例外

ff.Filters[f.GroupName].Add(f.FilterName, f.filterValue);

它显示以下错误

  

字典中没有给定的密钥

出了什么问题?任何人都可以帮助我

1 个答案:

答案 0 :(得分:1)

更改此代码:

ff.Filters[f.GroupName].Add(f.FilterName, f.filterValue);

要:

ff.Filters.Add(f.GroupName, new Dictionary<string, List<string>>() 
 { {f.FilterName, f.filterValue} });

希望这能解决您的问题。

查看此How to: Initialize a Dictionary with a Collection Initializer (C# Programming Guide)