将字典转换为 Json

本文关键字:Json 转换 字典 | 更新日期: 2023-09-27 18:33:26

我正在使用以下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 格式的键值对列表。

将字典转换为 Json

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

另外,如果 collListItem 是IEnumerable<ListItem>的(看起来是这样,因为你使用 foreach 循环遍历它),你不需要逐项构建字典。

尝试:

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