用了 mvc 有一段时间了,慢慢的熟悉起来了,也渐渐的发现了 mvc 的一些缺点,比如当我们返回 Json(new{}) 的时候没办法做到将首字母转换成小写、日期再序列化过后是时间戳需要到前台重新处理或者提在在对象中处理,这些都很不方便,用起来相当不舒服,所有在参考了一些其他的资料以后就重写了这个 json 序列化的方法。全程没什么难点,和自身序列化不同的地方在于放弃了微软自带的 json 序列化方法而该用了第三方的 json.net 的序列化框架。下面就是实现过程。
1. 新建一个类 CustomesJsonResult 继承自 mvc 自带的 JsonResult, 重写它的 ExecuteResult 方法。
- public class CustomsJsonResult: JsonResult {
- 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;
- }
- var jsonSerizlizerSetting = new JsonSerializerSettings();
- //设置取消循环引用
- jsonSerizlizerSetting.MissingMemberHandling = MissingMemberHandling.Ignore;
- //设置首字母小写
- jsonSerizlizerSetting.ContractResolver = new CamelCasePropertyNamesContractResolver();
- //设置日期的格式为:yyyy-MM-dd
- jsonSerizlizerSetting.DateFormatString = "yyy-MM-dd";
- var json = JsonConvert.SerializeObject(Data, Formatting.None, jsonSerizlizerSetting);
- response.Write(json);
- }
- }
至此整个重写已经完成(当然了你可以随意添加自己的设置根据自己需求),剩下就是怎么使用了:
1. 我们需要新建一个 BaseController 并继承自 Controller 类。如下:
- public class BaseAdminController: Controller {
- protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior) {
- return new CustomsJsonResult {
- Data = data,
- ContentType = contentType,
- ContentEncoding = contentEncoding,
- JsonRequestBehavior = behavior
- };
- }
- }
至此整个重写和使用已经完成了,后面我们只需要在新建控制器的时候继承自 BaseController 就可以了,当我们返回 josn 的时候就能看到们想要的结果。
网上类似的例子很多,我也参考了其它很多自恋,在此就不一一例举了。
来源: http://www.cnblogs.com/mengqin/p/Mvc.html