ASP.NET MVC 3控制器.Json方法序列化不查看DataMember Name attribure

WHI*_*LOR 4 asp.net-mvc serialization json controller

在我的课上我得到了:

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

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

如果我使用System.Runtime.Serialization.Json的序列化,那么就可以正常工作了.

有什么不对?

Dar*_*rov 12

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

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

例如:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在你的控制器动作中:

public ActionResult Foo()
{
    var model = ...
    return new MyJsonResult { Data = model };
}
Run Code Online (Sandbox Code Playgroud)