gpt4 book ai didi

c# - ASP.NET MVC : Json(IDictionary) 转换为键值对数组

转载 作者:太空狗 更新时间:2023-10-30 01:16:42 24 4
gpt4 key购买 nike

如果我有一个 IDictionary<string, string> MyDictionary类似于:

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

在我的 MVC Controller 中,我有一个这样的方法:

[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 结果覆盖了 Controller 中的这种行为,我的问题就解决了。

最佳答案

使用默认的 Json 序列化程序 (Json.Net),它应该从 Dictionary<string, string> 返回以下 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 );
}

关于c# - ASP.NET MVC : Json(IDictionary<string, string>) 转换为键值对数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34299730/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com