asp.net mvc4将无法正确反序列化并从json绑定Dictionary <string,List >
JSON.NET反序列化很好,但无论mvc用于控制器参数绑定barfs很难。 我可以做任何其他工作吗?
位:
public partial class Question { public Dictionary<string, List> TemporaryExtendedProperties { get; set; } }
和控制器方法
[HttpPost] public JsonResult SaveQuestions(Question[] questions) { var z = JsonConvert.DeserializeObject( "{'Options':[{'PropKey':'asdfasd','PropVal':'asdfalkj'},{'PropKey':'fdsafdsafasdfas','PropVal':'fdsafdas'}]}", typeof (Dictionary<string, List>)) as Dictionary<string, List>; //this deserializes perfectly. z is exactly what I want it to be //BUT, questions is all wrong. See pic below //lots of code snipped for clarity, I only care about the incoming questions object return Utility.Save(questions); }
这就是MVC为我提供的这个精确的字符串(从小提琴手中拉出来,附加内容为你的阅读乐趣而剪辑)
"TemporaryExtendedProperties":{"Options": [{"PropKey":"NE","PropVal":"NEBRASKA"}, {"PropKey":"CORN","PropVal":"CHILDREN OF"}, {"PropKey":"COW","PropVal":"MOO"}]}
为什么MVC会破坏这个完美的json字符串的绑定,我怎么能不这样做呢? 我完全控制了json结构和创建。
编辑
我尝试将Question.TemporaryExtendedProperties的类型更改为List<KeyValuePair<string, List>>
,但这也不起作用。 这是新的json(它与System.Web.Script.Serialization.JavaScriptSerializer
序列化对象的内容完全匹配!)
{ TemporaryExtendedProperties: [ { Key: 'Options', Value: [ { PropKey: 'NEBRASKA', PropVal: 'NE' }, { PropKey: 'DOG', PropVal: 'CORN' }, { PropKey: 'MEOW???', PropVal: 'COW' } ] } ] }
那也行不通。 它被控制器反序列化为List
,计数为1(如预期的那样),但Key
和Value
都为null
。 Json.NET再次完美地处理它。
啊。
我最终只是删除了字典的需要。 新代码如下所示:
//Other half is autogenerated by EF in models folder public partial class Question { public List TemporaryExtendedProperties { get; set; } } //Other half is autogenerated by EF in models folder public partial class QuestionExtendedProp { public string DictionaryKeyValue { get; set; } }
mvc处理这个很好。 我的控制器现在看起来像这样
[HttpPost] public JsonResult SaveQuestions(Question[] questions) { foreach (var q in questions) { //do regular question processing stuff //20 lines later IEnumerable> ExtendedPropGroups = q.TemporaryExtendedProperties.GroupBy(x => x.DictionaryKeyValue); foreach (IGrouping group in ExtendedPropGroups) { string groupKey = group.Key; foreach (var qexp in group) { //do things here } } } //rest of the stuff now that I've processed my extended properties...properly return Utility.SaveQuestions(questions); }