ASP.NET MVC 3控制器以.json方法序列化不看数据成员名称attribure [英] ASP.NET MVC 3 controller .Json method serialization doesn't look at DataMember Name attribure

查看:175
本文介绍了ASP.NET MVC 3控制器以.json方法序列化不看数据成员名称attribure的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的课堂我已经得到了:

In my class i've got:

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

传递对象通过控制器的JSON(OBJ)的retruns System.Web.Mvc.JsonResult后:我有序列化JSON:{成员:...}而不是{jsonMemberName:...},所以它不T看看数据成员(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 everithing的作品系列化细如预期。

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

什么可能是错的?

推荐答案

借助 JsonResult 动作,你是从控制器动作返回(使用返回JSON(...))内依赖于<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx\">JavaScriptSerializer类。此类不考虑任何数据成员属性的模型。

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方法序列化不看数据成员名称attribure的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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