优秀的编程知识分享平台

网站首页 > 技术文章 正文

自己写的一个json序列化类(json 序列化)

nanyue 2024-08-21 19:40:55 技术文章 3 ℃

由于公司最近项目用到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方法即可。



最近发表
标签列表