ASP.NET MVC 3 控制器 .Json 方法序列化不考虑 DataMember 名称属性
在我的班级中,我得到了:
[DataMember(Name = "jsonMemberName", EmitDefaultValue = false,
IsRequired = false)]
public List<string> Member { get; set; }
通过重新运行 System.Web.Mvc.JsonResult 的控制器的 Json(obj) 传递对象后:我得到了序列化的 json: {Member:...} 但不是 {jsonMemberName:... },所以它不会查看 DataMember(Name = "jsonMemberName")。
如果我使用 System.Runtime.Serialization.Json 的序列化,一切都会按预期正常工作。
有什么问题吗?
In my class i've got:
[DataMember(Name = "jsonMemberName", EmitDefaultValue = false,
IsRequired = false)]
public List<string> Member { get; set; }
After passing the object through controller's Json(obj) that retruns System.Web.Mvc.JsonResult: i've got serialized json: {Member:...} but not {jsonMemberName:...}, so it doesn't look at DataMember(Name = "jsonMemberName").
If I use serialization from System.Runtime.Serialization.Json everithing's works fine as expected.
What can be wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您从控制器操作(使用
return Json(...)
)在内部依赖于 JavaScriptSerializer 类。此类不考虑模型上的任何DataMember
属性。您可以编写一个自定义 ActionResult,它使用 System.Runtime.Serialization.Json 命名空间中的序列化器。
例如:
然后在您的控制器操作中:
The JsonResult action which you are returning from the controller action (using
return Json(...)
) internally relies on the JavaScriptSerializer class. This class doesn't take into account anyDataMember
attributes on your model.You could write a custom ActionResult which uses the serializer in the
System.Runtime.Serialization.Json
namespace.For example:
and then in your controller action:
System.Web.Mvc.JsonResult
使用旧的JavaScriptSerializer
类,它不了解有关 DataAnnotations 程序集的任何信息。您需要使用 DataContractJsonSerializer 。如果您愿意,可以在 JsonResult 上使用它:(
我参考了 ASP.NET MVC 源代码来创建它。不确定我是否必须以某种方式相信它。好吧,除了这个之外,就是这样。 :))
您还可以将其添加到控制器继承的基类中:
System.Web.Mvc.JsonResult
usea the oldJavaScriptSerializer
class, which doesn't know anything about the DataAnnotiations assembly. You need to use the DataContractJsonSerializer instead.You can use this instead on JsonResult if you so desire:
(I referenced the ASP.NET MVC source code to create this. Not sure if I have to credit it in some way. Well, more than this aside already is, that is. :))
You can also add this to a base class from which your controllers inherit: