【问题标题】:Convert dictionary to Json将字典转换为 Json
【发布时间】:2016-02-05 13:15:09
【问题描述】:

我正在使用以下 ASP MVC 代码将字典转换为 JsonResult

public JsonResult docGet()
{
    ......

    Dictionary<string, string> dictionary = new Dictionary<string, string>();

    foreach (ListItem ListItem in collListItem)
    {
        dictionary.Add((ListItem["ID"], ListItem["Title"]);     
        }

return Json(Result, JsonRequestBehavior.AllowGet);
} 

此代码不起作用。结果是 []。如果我将字典类型更改为仅包含 1 个值的列表,则它正在工作。但是想要的结果是json格式的键值对列表。

【问题讨论】:

    标签: c# json asp.net-mvc list dictionary


    【解决方案1】:

    我认为您得到空结果的主要原因是因为您返回的是 Result,而不是您填充的 ​​dictionary 变量。

    此外,如果 collListItem 是 IEnumerable&lt;ListItem&gt;(看起来是这样,因为您正在使用 foreach 循环遍历它),您不需要逐项构建字典。

    试试:

    Dictionary<string,string> dictionary=collListItem.ToDictionary(c=>c["ID"],c=>c["Title"]);
    
    return Json(dictionary,JsonRequestBehavior.AllowGet);
    

    【讨论】:

      猜你喜欢
      • 2018-07-04
      • 2014-12-31
      • 1970-01-01
      • 1970-01-01
      • 2011-01-29
      • 1970-01-01
      • 1970-01-01
      • 2018-03-18
      相关资源
      最近更新 更多