我正在尝试将Json映射到Dictionary。早些时候,我使用了类型为' long' 。但是在实现映射之后,关键需要是#string; string或' object'。
现在我在c#中的类型定义是这样的:
public class StyleItemCreateCommand
{
public long StyleId { get; set; }
public Dictionary<String, string> SelectedItemToColorMap { get; set; }
}
我生成的json是这样的:
{"StyleId":"1710","SelectedItemToColorMap":{"1391":"583","21531":"7733"}}
但仍然不知何故它没有被映射。我使用asp.net mvc控制器作为服务,由jquery客户端使用。
MVC方法签名如下:
[HttpPost]
public ActionResult Create(StyleItemCreateCommand command)
{
}
字典对象始终为null。任何帮助表示赞赏。感谢。
答案 0 :(得分:0)
我认为发生这种情况的原因是
"SelectedItemToColorMap":{"1391":"583","21531":"7733"}
是一个对象和你的StyleItemCreateCommand class定义了一个Dictionary。将类属性更改为:
public object SelectedItemToColorMap { get; set; }
你应该能够看到这些值。然后,您可以重新设计您的课程。 或者通过围绕{}和[]将SelectedItemToColorMap转换为一组键值项来修改json。
<强>更新强> 刚刚在asp.net mvc 4中尝试了一个简单的视图
<input type="button" value="click1" id="click1" />
@Scripts.Render("~/bundles/jquery")
<script>
$(function () {
//this is called by a Get action on the controller
$('#click1').click(function (e) {
var jsonObject = { "StyleId": "1710", "SelectedItemToColorMap": { "1391": "583", "21531": "7733" } };
$.ajax({
url: "@Url.Action("Create")",
type: "POST",
data: JSON.stringify(jsonObject),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (response) {
//process error;
},
success: function (response) {
//process success;
}
});
});
});
</script>
以上内容出现在视图正文中。控制器是
[HttpPost]
public ActionResult Create(StyleItemCreateCommand command)
{
if (command != null) {
string value1 = command.SelectedItemToColorMap["1391"];
string value2 = command.SelectedItemToColorMap["21531"];
Debug.Assert(value1 == "583" && value2 == "7733");
}
return View();
}
使用你的StyleItemCreateCommand - 这一切都有效。好的,上面使用JSON.stringify(jsonObject)所以你的json对象是什么格式实际来自post请求?看到请求体(例如,在网络部分下使用chrome开发人员工具)会很有趣。
.Net序列化(此处未使用)将把请求包装在.d对象中作为防止代码自动执行的安全措施,这可能是发生了什么?
答案 1 :(得分:0)
现在搜索网络后我发现ASP.Net MVC不会隐含地进行。找到这个答案: [https://stackoverflow.com/a/15220050/756722]