【问题标题】:ASP.NET MVC: Json(IDictionary<string, string>) converts to array of key-value pairsASP.NET MVC:Json(IDictionary<string, string>) 转换为键值对数组
【发布时间】:2015-12-15 21:28:10
【问题描述】:

如果我有一个类似这样的IDictionary&lt;string, string&gt; MyDictionary

{
    {"foo", "bar"},
    {"abc", "xyz"}
}

在我的 MVC 控制器中,我有一个类似这样的方法:

[HttpPost]
public JsonResult DoStuff()
{
    return Json(MyDictionary);
}

...它发回类似的东西:

[
 {"Key":"foo", "Value":"bar"},
 {"Key":"abc", "Value":"xyz"}
]

我期待(并且想要)这样的东西:

{
 "foo":"bar",
 "abc":"xyz"
}

我怎样才能做到这一点?

更新

因此,这与该项目是从使用自定义 JSON 序列化程序的 ASP.NET 2.0 应用程序升级而来的事实直接相关;显然,为了向后兼容,他们将其设为 MVC 应用程序中的默认 JSON 序列化程序。最终,我用 Json.NET 结果覆盖了我的控制器中的这种行为,我的问题得到了解决。

【问题讨论】:

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


【解决方案1】:

使用默认的 Json 序列化程序(Json.Net),它应该从 Dictionary&lt;string, string&gt; 返回以下 JSON 结构

{"Foo": "TTTDic", "Bar": "Scoo"}

使用您的操作方法:

[HttpPost]
public JsonResult DoStuff()
{
    var MyDictionary = new Dictionary<string, string>();
    MyDictionary.Add("Foo", "TTTDic");
    MyDictionary.Add("Bar", "Scoo");
    return Json(MyDictionary);
}

MVC5MVC6 中验证了这一点。

如果您仍然遇到问题,为什么不创建一个具有您想要的属性的简单 POCO?

public class KeyValueItem
{
    public string Foo { set; get; }
    public string Abc { set; get; }
}

然后创建一个对象,设置属性值并将其作为 JSON 发送。

[HttpPost]
public JsonResult DoStuff()
{
  var item = new KeyValueItem
  {
      Foo="Bee",
      Abc="Scoo"
  };
  return Json(item );
}

【讨论】:

  • 仅说明:POCO 仅在字典由具体对象构成时才有效。通常人们将这样的字典用于动态值。
  • 正是我的情况;在这种情况下,我不能使用 POCO,因为“属性”是动态的。
  • 你的版本是什么?我在 MVC5 和 6 中验证了它将字典转换为你想要的 JSON 格式。
  • 看起来当此应用程序从旧版 ASP.NET 升级到 MVC5 时,他们特意指定了一个自定义 json 序列化程序以实现向后兼容性(他们在升级之前使用它)。我会将此标记为答案,因为它让我在寻找什么方面走上了正确的道路。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-24
  • 2014-03-23
  • 1970-01-01
  • 2010-10-11
相关资源
最近更新 更多