JSON 用于序列化为字典的结构

JSON structure for serializing into Dictionary

在 MVC 控制器中,我有以下代码

 [HttpPost]
 public ActionResult One(Dictionary<Guid, int[]> groups)
 {
   return Json(groups);
 }

我需要提供什么 json 结构才能将其正确序列化到词典中? 在下面尝试过:

{
  "Key": "4e89af43-59c8-492b-b646-1185e3f8776c",
  "Value": [1, 2, 3, 4, 5]
}

{
    "groups": {
        "Key": "4e89af43-59c8-492b-b646-1185e3f8776c",
        "Value": [1, 2, 3, 4, 5]
    }
}

如果要序列化成"Dictionary",需要如下结构:

{
    "Key": "Value",
    "Key": "Value",
    "Key": "Value"
}

在您的情况下,它将是以下对象:

{
    "4e89af43-59c8-492b-b646-1185e3f8776c": [1, 2, 3, 4, 5],
    "4e89af43-1234-492b-b646-1185e3f8776c": [0, -1, -2],
    "4e89af43-59c8-5678-b646-1185e3f8776c": [7]
}

在ASP.NET中的JSON请求方面,您可能需要将其包装在与变量名称相对应的对象中:

{
    groups: {
        "4e89af43-59c8-492b-b646-1185e3f8776c": [1, 2, 3, 4, 5],
        "4e89af43-1234-492b-b646-1185e3f8776c": [0, -1, -2],
        "4e89af43-59c8-5678-b646-1185e3f8776c": [7]
    }
}

至少,Dictionary<string, int[]>.
肯定是这样的 您有一个 Guid 作为键,我希望 ASP.NET 能够将 Guid 正确序列化为字符串。

似乎 GUID 在字典中时不打算序列化。这是我收到的错误

所以我不得不将我的字典更改为下面的内容,并像下一段代码一样发送参数

[HttpPost]
public ActionResult One(Dictionary<string, int[]> groups)
 {
   return Json(groups);
 }

JSON 输入

{"groups":[
    {
        "Key": "4e89af43-59c8-492b-b646-1185e3f8776c",
        "Value": [1, 2, 3, 4, 5]
    }
]}

感谢所有帮助过的人