3

我有一个在我的 ASP.Net MVC4 应用程序中返回 JsonResult 的操作。我将 Data 属性设置为预定义类的数组。我的问题是我想用不同的属性名称进行序列化。无论我使用什么属性,对象都会使用预定义的属性名称进行序列化。我试过以下没有结果:

[DataMember(Name = "iTotalRecords")]
[JsonProperty(PropertyName = "iTotalRecords")]
public int TotalRecords { get; set; }

我知道“iTotalRecords”看起来很傻,但这个动作是为了支持一个需要“iTotalRecords”而不是“TotalRecords”的jQuery插件。当然,我想使用在我的代码隐藏中有意义的名称。

使用什么序列化器来解析 JsonResult?有什么我可以做的,还是我必须重新考虑将 JsonResult 作为操作结果返回?

4

3 回答 3

4

使用什么序列化器来解析 JsonResult?

JavaScriptSerializer.

有什么我可以做的,还是我必须重新考虑将 JsonResult 作为操作结果返回?

想到了两种可能:

  • 定义视图模型,然后将您的域模型映射到视图模型
  • 编写使用 Json.NET 或 DataContractJsonSerializer 的自定义操作结果,并允许您控制序列化属性的名称。以下问题说明了这一点。
于 2012-09-19T15:02:42.617 回答
4

感谢您的建议。我继续创建了一个使用 Json.Net 的 ActionResult:

public class JsonNetActionResult : ActionResult
{
    public Object Data { get; private set; }

    public JsonNetActionResult(Object data)
    {
        this.Data = data;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        context.HttpContext.Response.ContentType = "application/json";
        context.HttpContext.Response.Write(JsonConvert.SerializeObject(Data));
    }
}

仅供参考,看起来 Json.Net 尊重 [DataMember] 和 [JsonProperty],但如果它们不同,[JsonProperty] 将胜过 [DataMember]。

于 2012-09-19T15:27:37.443 回答
1

我在这里和 SO 上找到了部分解决方案

public class JsonNetResult : ActionResult
    {
        public Encoding ContentEncoding { get; set; }
        public string ContentType { get; set; }
        public object Data { get; set; }

        public JsonSerializerSettings SerializerSettings { get; set; }
        public Formatting Formatting { get; set; }

        public JsonNetResult(object data, Formatting formatting)
            : this(data)
        {
            Formatting = formatting;
        }

        public JsonNetResult(object data):this()
        {
            Data = data;
        }

        public JsonNetResult()
        {
            Formatting = Formatting.None;
            SerializerSettings = new JsonSerializerSettings();
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");
            var response = context.HttpContext.Response;
            response.ContentType = !string.IsNullOrEmpty(ContentType)
              ? ContentType
              : "application/json";
            if (ContentEncoding != null)
                response.ContentEncoding = ContentEncoding;

            if (Data == null) return;

            var writer = new JsonTextWriter(response.Output) { Formatting = Formatting };
            var serializer = JsonSerializer.Create(SerializerSettings);
            serializer.Serialize(writer, Data);
            writer.Flush();
        }
    }

所以在我的控制器中,我可以做到这一点

        return new JsonNetResult(result);

在我的模型中,我现在可以拥有:

    [JsonProperty(PropertyName = "n")]
    public string Name { get; set; }

请注意,现在,您必须将 设置为JsonPropertyAttribute要序列化的每个属性。

于 2014-03-28T11:16:35.220 回答