JSON.NET反序列化很好,但无论mvc用于控制器参数绑定barfs很难。我可以做任何其他事情来完成这项工作吗?
位:
public partial class Question
{
public Dictionary<string, List<QuestionExtendedProp>> 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<QuestionExtendedProp>>)) as Dictionary<string, List<QuestionExtendedProp>>;
//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<QuestionExtendedProp>>>
,但这也不起作用。这是新的json(它与System.Web.Script.Serialization.JavaScriptSerializer
序列化对象的确切匹配!)
{
TemporaryExtendedProperties: [
{
Key: 'Options',
Value: [
{
PropKey: 'NEBRASKA',
PropVal: 'NE'
},
{
PropKey: 'DOG',
PropVal: 'CORN'
},
{
PropKey: 'MEOW???',
PropVal: 'COW'
}
]
}
]
}
这也不起作用。控制器将其反序列化为List<blah,blah>
,计数为1(按预期方式),但Key
和Value
均为null
。 Json.NET再次完美地处理它。
呃。
答案 0 :(得分:1)
我最终只是删除了字典的需要。新代码如下所示:
//Other half is autogenerated by EF in models folder
public partial class Question
{
public List<QuestionExtendedProp> 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<IGrouping<string, QuestionExtendedProp>> ExtendedPropGroups = q.TemporaryExtendedProperties.GroupBy(x => x.DictionaryKeyValue);
foreach (IGrouping<string, QuestionExtendedProp> 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);
}