ASP.NET MVC 3 controller .Json method serialization doesn't look at DataMember Name attribure

前端 未结 2 1373
借酒劲吻你
借酒劲吻你 2020-12-06 08:13

In my class i\'ve got:

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


        
2条回答
  •  温柔的废话
    2020-12-06 08:35

    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.

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

    For example:

    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 };
    }
    

提交回复
热议问题