ASP.NET MVC 3 控制器 .Json 方法序列化不查看 DataMember Name 属性 [英] ASP.NET MVC 3 controller .Json method serialization doesn't look at DataMember Name attribure

查看:18
本文介绍了ASP.NET MVC 3 控制器 .Json 方法序列化不查看 DataMember Name 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的课堂上,我有:

[DataMember(Name = "jsonMemberName", EmitDefaultValue = false, 
    IsRequired = false)]
public List<string> Member { get; set; }

在通过控制器的 Json(obj) 重新运行 System.Web.Mvc.JsonResult 传递对象后:我已经序列化了 json: {Member:...} 但不是 {jsonMemberName:...},所以它没有不看 DataMember(Name = "jsonMemberName").

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").

如果我使用 System.Runtime.Serialization.Json 中的序列化,一切都会按预期正常工作.

If I use serialization from System.Runtime.Serialization.Json everithing's works fine as expected.

有什么问题?

推荐答案

JsonResult 您从控制器操作返回的操作(使用 return Json(...))在内部依赖于 JavaScriptSerializer 类.此类不考虑模型上的任何 DataMember 属性.

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 any DataMember attributes on your model.

您可以编写一个使用 System.Runtime.Serialization.Json 命名空间中的序列化程序的自定义 ActionResult.

You could write a custom ActionResult which uses the serializer in the System.Runtime.Serialization.Json namespace.

例如:

public class MyJsonResult : JsonResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        var response = context.HttpContext.Response;
        if (!string.IsNullOrEmpty(ContentType))
        {
            response.ContentType = ContentType;
        }
        else
        {
            response.ContentType = "application/json";
        }
        if (ContentEncoding != null)
        {
            response.ContentEncoding = this.ContentEncoding;
        }
        if (Data != null)
        {
            var serializer = new DataContractJsonSerializer(Data.GetType());
            serializer.WriteObject(response.OutputStream, Data);
        }
    }
}

然后在您的控制器操作中:

and then in your controller action:

public ActionResult Foo()
{
    var model = ...
    return new MyJsonResult { Data = model };
}

这篇关于ASP.NET MVC 3 控制器 .Json 方法序列化不查看 DataMember Name 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆