mvc 使用Newtonsoft.Json进行序列化json数据-程序员宅基地

技术标签: c#  测试  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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_30375247/article/details/95304224

智能推荐

pgsql关于json类型的简单用法,json赋值、json数组、json取值_pgsql json-程序员宅基地

文章浏览阅读8.6k次。PostgreSQL json数据类型的简单操作。_pgsql json

小程序picker-view标签属性value不生效问题_picker-view value变更无效-程序员宅基地

文章浏览阅读743次。微信小程序picker value无效_picker-view value变更无效

谷歌浏览器的跨域设置、配置、新老版本Chrome_chrome允许跨域-程序员宅基地

文章浏览阅读5k次,点赞6次,收藏12次。谷歌浏览器的跨域设置、配置、新老版本Chrome_chrome允许跨域

OpenCV笔记20:在Python中使用OpenCV查找和绘制轮廓_python中opencv找园轮廓并画出轮廓-程序员宅基地

文章浏览阅读619次。1、学习目标在Python中如何使用OpenCV查找轮廓和绘制轮廓。2、使用的函数方法轮廓是形状分析和物体检测和识别的有用工具。函数从二进制图像中检索轮廓。cv2.findContours()cv2.drawContours()3、程序结果..._python中opencv找园轮廓并画出轮廓

springboot点餐订餐系统 毕业设计-附源码51361_基于springboot的订餐系统设计论文-程序员宅基地

文章浏览阅读1.8k次,点赞45次,收藏35次。点餐订餐系统的设计与实现摘要随着互联网趋势的到来,各行各业都在考虑利用互联网将自己推广出去,最好方式就是建立自己的互联网系统,并对其进行维护和管理。在现实运用中,应用软件的工作规则和开发步骤,采用Java技术建设点餐订餐系统。本设计主要实现集人性化、高效率、便捷等优点于一身的点餐订餐系统,完成首页、轮播图、公告信息、资源管理(美食资讯、资讯分类)商城管理(美食点餐、分类列表、订单列表)系统用户(管理员、普通用户、卖家)等功能模块。系统通过浏览器与服务器进行通信,实现数据的交互与变更。只需_基于springboot的订餐系统设计论文

《Effective C++读书笔记》--条款34:区分接口继承和实现继承_条款34:区分接口继承和实现继承。-程序员宅基地

文章浏览阅读257次。当我们设计一个类的时候,我们会希望其子类只继承成员函数的接口,但有时候又希望其继承接口和实现,但又希望能重写他们所继承的接口和实现或者不允许重写任何东西。我们首先要明确public继承含义,即is-A的关系,对于基类成立的所有条件,对其public继承的子类一定成立,反之则不然。当我们希望子类继承该函数的接口时,我们可将该函数在基类中定义为纯虚函数,此时基类是不可被实例化的,其中代表的含义是“_条款34:区分接口继承和实现继承。

随便推点

kaggle —— Isolatede Sigh Language Recognition_kaggle language里-程序员宅基地

文章浏览阅读120次。note:tf.constant 定义一个常量tf.transpose 转置python装饰器就是用于拓展原来函数功能的一种函数normalisation_correction 这个矩阵用于校正相机的拍摄方向,将左手调整为右手,右手调整为左手。pad_edge 用于在给定张量的左侧或右侧填充一定数量的重复元素@tf.function 装饰器 装饰了一个 call 方法,用于处理输入数据。_kaggle language里

CentOS 8.0 基本配置_centos8 server getenforced-程序员宅基地

文章浏览阅读1.3k次。1. 修改主机名[root@localhost ~]# hostnamelocalhost.localdomain[root@localhost ~]# vi /etc/hostname //将文件中的“localhost.localdomain”修改为“Server”,需重启后方可生效localhost.localdomain -> Server2. 关闭selinux[root@localhost ~]#..._centos8 server getenforced

现代激光原理与技术课后习题答案(个人版)第三章-程序员宅基地

文章浏览阅读349次,点赞9次,收藏9次。现代激光原理与技术课后习题答案(个人版)仅仅是本人在课程学习时的笔记以及根据老师所讲和各种资料总结的课后习题答案。文中的所有答案仅是本人个人想法,不一定正确,还望指正。主要的参考书是《现代激光原理与技术》

web服务器基础-程序员宅基地

文章浏览阅读1.5k次,点赞46次,收藏43次。www是world wide web的缩写,也就是全球信息广播的意思。通常说的上网就是使用www来查询用户所需要的信息。www可以结合文字、图形、影像以及声音等多媒体,并通过可以让鼠标单击超链接的方式将信息以Internet传递到世界各处去。与其他服务器类似,当你连接上www网站,该网站肯定会提供一些数据,而你的客户端则必须要使用可以解析这些数据的软件来处理,那就是浏览器。www服务器与客户端浏览器之间的连接图。

cpu温度监测 Turbo Boost Switcher Pro for mac最新-程序员宅基地

文章浏览阅读725次。Turbo Boost Switcher Pro是一款Mac电脑上的应用程序,旨在帮助用户控制和管理CPU的Turbo Boost功能。_turbo boost switcher

依赖和关联的对比和区别_依赖关系和关联关系的区别-程序员宅基地

文章浏览阅读1.8k次,点赞4次,收藏13次。关联理解分析关联的关系用实线加箭头的形式表示,箭头指向的类时被关联的类关联体现的关系比依赖更强关联(Association)关系是类与类之间的联接,它使一个类知道另一个类的属性和方法。关联可以是双向的,也可以是单向的。在Java语言中,关联关系一般使用成员变量来实现。UML图依赖和关联的区别● 从耦合性的角度对比发生依赖关系的两个类都不会增加属性。其中的一个类作为另一个类的方法的参数或是某个方法的变量发生关联关系的两个类,其中一个类作为另一个类的属性,属性是一种更为紧密的耦合关系,是_依赖关系和关联关系的区别