龙空技术网

自己写的一个json序列化类

鹅是程序猿 447

前言:

现在你们对“iisajaxjson文件”大体比较关切,大家都需要分析一些“iisajaxjson文件”的相关内容。那么小编在网络上网罗了一些关于“iisajaxjson文件””的相关文章,希望我们能喜欢,看官们快快来了解一下吧!

由于公司最近项目用到asp.net的mvc框架,在使用过程中发现一个问题,对<<dynamic>,List<dynamic>这类集合进行序列化的时候,前端获取的数据格式非常怪异。

 [AjaxOnly] [HttpGet] public virtual JsonResult ListData() { ..... IEnumerable<dynamic> dataList = ListBll.List(MvcContext);、、 return Json(dataList); }

研究了mvc的文档后,决定对用大名鼎鼎的 NewtonJson重写Json方法,首先定义一个类,并继承JsonResult,代码如下:

using PageAdmin.Utils;namespace System.Web.Mvc{ //采用Newtonsoft.Json定义新的Jsonresult,默认的JsonResult采用微软自带的系列化,对IEnumerable<dynamic>类型数据序列化后格式混乱。 public class NewtonJson:JsonResult { public override void ExecuteResult(ControllerContext context) { if (context == null) throw new ArgumentNullException("context"); if (context.HttpContext == null || context.HttpContext.Response == null) return; context.HttpContext.Response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/json"; if (ContentEncoding != null) context.HttpContext.Response.ContentEncoding = ContentEncoding; if (Data != null) context.HttpContext.Response.Write(JsonHelper.JsonParse(Data)); } internal static JsonResult Json(object data) { var jsonResult = new NewtonJson() { Data = data, JsonRequestBehavior = JsonRequestBehavior.AllowGet, ContentType = "application/json;charset=utf-8", }; return jsonResult; } }}

然后再控制器中重写Json方法。

 protected JsonResult NewJson(object data) { return NewtonJson.Json(data); }

以后凡是需要系列化的直接用NewJson方法即可。



标签: #iisajaxjson文件