mvc 使用Newtonsoft.Json进行序列化json数据

.net mvc服务器段返回json数据采用的是System.Web.Script.Serialization进行序列化的,但是.net自带的序列化工具没有Newtonsoft.Json第三方好用,我们现在来使Newtonsoft.Json替换用JsonResult,打造属于自己的jsonResult。

具体的代码如下

添加引用

[csharp]  view plain  copy
 
  1. using System;  
  2. using System.IO;  
  3. using System.Text;  
  4. using System.Web.Mvc;  
  5. using Aft.Build.Common;  
  6. using Newtonsoft.Json;  
  7. using Newtonsoft.Json.Serialization;  



[csharp]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. public class JsonNetResult : JsonResult  
  2.     {  
  3.         public JsonNetResult()  
  4.         {  
  5.             Settings = new JsonSerializerSettings  
  6.             {  
  7.                 ReferenceLoopHandling = ReferenceLoopHandling.Error  
  8.             };  
  9.         }  
  10.         public JsonNetResult(object data, JsonRequestBehavior behavior = JsonRequestBehavior.AllowGet, string contentType = null, Encoding contentEncoding = null)  
  11.         {  
  12.             Data = data;  
  13.             JsonRequestBehavior = behavior;  
  14.             ContentEncoding = contentEncoding;  
  15.             ContentType = contentType;  
  16.         }  
  17.   
  18.         private JsonSerializerSettings _settings;  
  19.         public JsonSerializerSettings Settings  
  20.         {  
  21.             get  
  22.             {  
  23.                 _settings = _settings ?? new JsonSerializerSettings();  
  24.                 _settings.ContractResolver = new CamelCasePropertyNamesContractResolver();  
  25.                 return _settings;  
  26.             }  
  27.             private set { _settings = value; }  
  28.         }  
  29.   
  30.         public override void ExecuteResult(ControllerContext context)  
  31.         {  
  32.   
  33.             if (context == null)  
  34.                 throw new ArgumentNullException("context");  
  35.             if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))  
  36.                 throw new InvalidOperationException("JSON GET is not allowed");  
  37.             var response = context.HttpContext.Response;  
  38.             response.ContentType = string.IsNullOrEmpty(ContentType) ? "application/json" : ContentType;  
  39.   
  40.             if (ContentEncoding != null)  
  41.                 response.ContentEncoding = ContentEncoding;  
  42.             if (Data == null)  
  43.                 return;  
  44.             var scriptSerializer = JsonSerializer.Create(Settings);  
  45.             using (var sw = new StringWriter())  
  46.             {  
  47.                 scriptSerializer.Serialize(sw, Data);  
  48.                 response.Write(sw.ToString());  
  49.             }  
  50.         }  
  51.     }  

这里我使用Newtonsoft.Json的 ContractResolver是CamelCasePropertyNamesContractResolver(即大小写格式)进行序列化数据。

 

使用方式就跟使用jsonResult方式一样。

但是每次使用new jsonResult这种方式真的很烦人,我希望能在mvc controller  action中使用json方法一样返回一个json数据。

接下来我们写两个controller扩展方法,具体代码实现如下:

 

[csharp]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. <pre name="code" class="csharp">using System;  
  2. using System.Linq;  
  3. using System.Web.Mvc;  
  4. using Aft.Build.MvcWeb.Models;  
  5.   
  6. namespace Aft.Build.MvcWeb.Common.Extensions  
  7. {  
  8.     public static class ControllerExtensions  
  9.     {  
  10.         public static ActionResult JsonNetResult(this Controller controller, Object data)  
  11.         {  
  12.             return new JsonNetResult(data);  
  13.         }  
  14.         public static ActionResult JsonNetResult<T>(this Controller controller, IQueryable<T> query, KendoPagedFilter filter)  
  15.         {  
  16.             var data = DataSourceResult<T>.From(query, filter);  
  17.             return controller.JsonNetResult(data);  
  18.         }  
  19.     }  
  20. }  



 

 
 


使用方式:

 

添加引用:

1.把扩展所在的地方添加引用

[csharp]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. using Aft.Build.MvcWeb.Common.Extensions;  
[csharp]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. [HttpPost]  
  2.        public ActionResult List(SearchFilter filter)  
  3.        {  
  4.            var query = _countryRepository.AsQueryable();  
  5.            if (!string.IsNullOrEmpty(filter.Name))  
  6.            {  
  7.                query = query.Where(e => e.Name.Contains(filter.Name));  
  8.            }  
  9.            return this.JsonNetResult(query, filter);  
  10.        }  


或者是

 

 

[csharp]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. [HttpPost]  
  2.         public ActionResult Update(ObjectId id, Employee employee)  
  3.         {  
  4.             employee.Id = id;  
  5.             var result = _employeeTask.Save(employee);  
  6.             return this.JsonNetResult(result);  
  7.         }  


再或者是:

 

 

[csharp]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. [HttpPost]  
  2.         public ActionResult Del(ObjectId id)  
  3.         {  
  4.             _countryRepository.Delete(id);  
  5.             return new JsonNetResult(true);  
  6.         }  


这样,总算是大功告成了。

 

总结:

1.mvc默认使用Json方法是在controller中使用JsonResult来返回json数据的。

2.前端json数据使用大小写格式更加正规,更加符合命名规范。

 

转自:http://blog.csdn.net/zhangyuanwei88/article/details/38556689

转载于:https://www.cnblogs.com/guoxibaijv/p/6526575.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值