使用JsonResult时,定义JSON字段名 [英] Define JSON field names when using JsonResult

查看:203
本文介绍了使用JsonResult时,定义JSON字段名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的ASP.Net应用MVC4返回JsonResult动作。我的数据属性设置为pre定义类的数组。我的问题是,我想用不同的属性名序列化。不管我用什么属性,对象序列化与pre定义的属性名称。我试过没有结果如下:

  [数据成员(NAME =iTotalRecords)]
[JsonProperty(属性名=iTotalRecords)]
公众诠释总记录{搞定;组; }

我知道iTotalRecords似乎很傻,但这个动作是用于支持jQuery插件,预计iTotalRecords而不是总记录。当然,我想用的名字,在我的code-背后意义。

什么串行用于解析JsonResult?有什么我能做的还是我必须重新思考返回JsonResult作为操作的结果?


解决方案

  

什么串行用于分析JsonResult?


<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx\"相对=nofollow> 的JavaScriptSerializer


  

有什么我能做的还是我必须重新思考返回JsonResult作为操作的结果?


两种可能性浮现在脑海中:


  • 定义视图模型,然后映射您的域模型视图模型

  • 编写使用Json.NET或DataContractJsonSerializer并允许您控制序列化属性的名称自定义操作的结果。在<一个href=\"http://stackoverflow.com/questions/1302946/asp-net-mvc-controlling-serialization-of-property-names-with-jsonresult\">following问题说明了这一点。

I have an action that returns a JsonResult in my ASP.Net MVC4 application. I'm setting the Data property to an array of pre-defined classes. My issue is that I want to serialize with different property names. No matter what attributes I use, the object is serialized with the pre-defined property names. I've tried the following with no results:

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

I know "iTotalRecords" seems silly, but this action is for supporting a jQuery plugin that expects "iTotalRecords" and not "TotalRecords". Of course, I want to use names that make sense in my code-behind.

What serializer is used to parse JsonResult? Is there anything I can do or do I have to re-think returning JsonResult as an action result?

解决方案

What serializer is used to parse JsonResult?

JavaScriptSerializer.

Is there anything I can do or do I have to re-think returning JsonResult as an action result?

Two possibilities come to mind:

  • define a view model and then map your domain model to the view model
  • write a custom action result that uses Json.NET or DataContractJsonSerializer and which allow you to control the names of the serialized properties. The following question illustrates this.

这篇关于使用JsonResult时,定义JSON字段名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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