.net mvc服务器段返回json数据采用的是System.Web.Script.Serialization进行序列化的,但是.net自带的序列化工具没有Newtonsoft.Json第三方好用,我们现在来使Newtonsoft.Json替换用JsonResult,打造属于自己的jsonResult。
具体的代码如下
添加引用
- using System;
- using System.IO;
- using System.Text;
- using System.Web.Mvc;
- using Aft.Build.Common;
- using Newtonsoft.Json;
- using Newtonsoft.Json.Serialization;
- public class JsonNetResult : JsonResult
- {
- public JsonNetResult()
- {
- Settings = new JsonSerializerSettings
- {
- ReferenceLoopHandling = ReferenceLoopHandling.Error
- };
- }
- public JsonNetResult(object data, JsonRequestBehavior behavior = JsonRequestBehavior.AllowGet, string contentType = null, Encoding contentEncoding = null)
- {
- Data = data;
- JsonRequestBehavior = behavior;
- ContentEncoding = contentEncoding;
- ContentType = contentType;
- }
- private JsonSerializerSettings _settings;
- public JsonSerializerSettings Settings
- {
- get
- {
- _settings = _settings ?? new JsonSerializerSettings();
- _settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
- return _settings;
- }
- private set { _settings = value; }
- }
- public override void ExecuteResult(ControllerContext context)
- {
- if (context == null)
- throw new ArgumentNullException("context");
- if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
- throw new InvalidOperationException("JSON GET is not allowed");
- var response = context.HttpContext.Response;
- response.ContentType = string.IsNullOrEmpty(ContentType) ? "application/json" : ContentType;
- if (ContentEncoding != null)
- response.ContentEncoding = ContentEncoding;
- if (Data == null)
- return;
- var scriptSerializer = JsonSerializer.Create(Settings);
- using (var sw = new StringWriter())
- {
- scriptSerializer.Serialize(sw, Data);
- response.Write(sw.ToString());
- }
- }
- }
这里我使用Newtonsoft.Json的 ContractResolver是CamelCasePropertyNamesContractResolver(即大小写格式)进行序列化数据。
使用方式就跟使用jsonResult方式一样。
但是每次使用new jsonResult这种方式真的很烦人,我希望能在mvc controller action中使用json方法一样返回一个json数据。
接下来我们写两个controller扩展方法,具体代码实现如下:
- <pre name="code" class="csharp">using System;
- using System.Linq;
- using System.Web.Mvc;
- using Aft.Build.MvcWeb.Models;
- namespace Aft.Build.MvcWeb.Common.Extensions
- {
- public static class ControllerExtensions
- {
- public static ActionResult JsonNetResult(this Controller controller, Object data)
- {
- return new JsonNetResult(data);
- }
- public static ActionResult JsonNetResult<T>(this Controller controller, IQueryable<T> query, KendoPagedFilter filter)
- {
- var data = DataSourceResult<T>.From(query, filter);
- return controller.JsonNetResult(data);
- }
- }
- }
使用方式:
添加引用:
1.把扩展所在的地方添加引用
- using Aft.Build.MvcWeb.Common.Extensions;
- [HttpPost]
- public ActionResult List(SearchFilter filter)
- {
- var query = _countryRepository.AsQueryable();
- if (!string.IsNullOrEmpty(filter.Name))
- {
- query = query.Where(e => e.Name.Contains(filter.Name));
- }
- return this.JsonNetResult(query, filter);
- }
或者是
- [HttpPost]
- public ActionResult Update(ObjectId id, Employee employee)
- {
- employee.Id = id;
- var result = _employeeTask.Save(employee);
- return this.JsonNetResult(result);
- }
再或者是:
- [HttpPost]
- public ActionResult Del(ObjectId id)
- {
- _countryRepository.Delete(id);
- return new JsonNetResult(true);
- }
这样,总算是大功告成了。
总结:
1.mvc默认使用Json方法是在controller中使用JsonResult来返回json数据的。
2.前端json数据使用大小写格式更加正规,更加符合命名规范。
转自:http://blog.csdn.net/zhangyuanwei88/article/details/38556689