Custom ASP.NET MVC JsonResult serialization results

In the recent development of the front page of the project using the jQuery plug-in of EasyUI, the Datebox component in the EasyUI Form is bound to the DateTime type data returned by ASP.NET MVC. The value is “\/Date(277630788015)\/”, so EasyUI displays the returned value without converting the date and directly displays it in the DateBox component. To solve this problem, there are actually Two ways:

  1. Extend the parser function of the datebox component of EasyUI to customize the date format, but there is a problem that if you use form.load data to assign the value to the datebox first, the parser method of the datebox will not be called, and the datebox can only be changed after the form is loaded. The value is a value in the format of “2011-11-3”;
  2. The second way is to modify the Json serialization method of ASP.NET MVC in this article, that is, to modify the serialization method of JsonResult. Let’s talk about this method in detail below.

First look at the source code of the Json method of the Controller in ASP.NET MVC:

 protected internal JsonResult Json(object data) {

            return Json(data, null /* contentType */);

        }

 

        protected internal JsonResult Json(object data, string contentType) {

            return Json(data, contentType, null /* contentEncoding */);

        }

 

        protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding) {

            return new JsonResult {

                Data = data,

                ContentType = contentType,

                ContentEncoding = contentEncoding

            };

        }

It can be seen that the key is still in the result class JsonResult. The source code of the JsonResult class is as follows:

[AspNetHostingPermission(System.Security.Permissions.SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]

    [AspNetHostingPermission(System.Security.Permissions.SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]

    public class JsonResult : ActionResult {

 

        public Encoding ContentEncoding {

            get;

            set;

        }

 

        public string ContentType {

            get;

            set;

        }

 

        public object Data {

            get;

            set;

        }

 

        public override void ExecuteResult(ControllerContext context) {

            if (context == null) {

                throw new ArgumentNullException("context");

            }

 

            HttpResponseBase response = context.HttpContext.Response;

 

            if (!String. IsNullOrEmpty(ContentType)) {

                response.ContentType = ContentType;

            }

            else {

                response.ContentType = "application/json";

            }

            if (ContentEncoding != null) {

                response.ContentEncoding = ContentEncoding;

            }

            if (Data != null) {

#pragma warning disable 0618

                JavaScriptSerializer serializer = new JavaScriptSerializer();

                response.Write(serializer.Serialize(Data));

#pragma warning restore 0618

            }

        }

    }

}

Seeing this, everyone should be clear about our modification goals. Yes, it is the ExecuteResult method. This method serializes Data objects into Json format. It can be seen that ASP.NET MVC uses the System.Web.Script.Serialization.JavaScriptSerializer class

Now that the goal is clear, let’s get started.

1. Extend the JsonResult class to customize a CustomJsonResult class, and rewrite the ExecuteResult method code as follows:

public class CustomJsonResult:JsonResult

    {

        public override void ExecuteResult(ControllerContext context)

        {

            if (context == null)

            {

                throw new ArgumentNullException("context");

            }

 

            HttpResponseBase response = context.HttpContext.Response;

 

            if (!String.IsNullOrEmpty(ContentType))

            {

                response.ContentType = ContentType;

            }

            else

            {

                response.ContentType = "application/json";

            }

            if (ContentEncoding != null)

            {

                response.ContentEncoding = ContentEncoding;

            }

            if (Data != null)

            {

#pragma warning disable 0618

              
                //Newtonsoft.Json.JsonConvert class
                response.Write(JsonConvert.SerializeObject(Data));

#pragma warning restore 0618

            }

        }

We are using the Newtonsoft.Json.JsonConvert class to serialize objects into Json. For the serialization comparison in .NET, please refer to the article: Using JSON as a data exchange format in .NET

  1. Extend the Controller to rewrite the Json method, the code is as follows:
 public class BaseController:Controller

    {

        protected override JsonResult Json(object data, string contentType, Encoding contentEncoding)

        {

            return new CustomJsonResult

            {

                Data = data,

                ContentType = contentType,

                ContentEncoding = contentEncoding

            };

        }

}

The following is the actual method we use, because the DateTime type of the Newtonsoft.Json.JsonConvert class can specify the type of serialized date as: [JsonConverter(typeof(IsoDateTimeConverter))], [JsonConverter(typeof(JavaScriptDateTimeConverter))]

[JsonConverter(typeof(IsoDateTimeConverter))] The serialized format is: 1981-03-16T00:20:12.1875 + 08:00

[JsonConverter(typeof(JavaScriptDateTimeConverter))]The serialized format is: new Date(-277630787812)

So we specify the DateTime attribute of the entity class as IsoDateTimeConverter, the code is as follows:

 

       [Field("P_Date", "Updated Date")]

       [JsonConverter(typeof(IsoDateTimeConverter))]

       public DateTime P_Date { get; set; }

The controller inherits from BaseController, and the return result of Action is still in JsonResult format. The code is as follows:

    public class GoodsController:BaseController

{

        public JsonResult List(string page, string rows)

        {

            Page thepage = new Page() { PageSize = 20, CurrentPage = 1 };

            if (!String.IsNullOrEmpty(rows))

            {

                thepage.PageSize = Convert.ToInt32(rows);

            }

 

            if (!String. IsNullOrEmpty(page))

            {

                thepage.CurrentPage = Convert.ToInt32(page);

            }

            Dictionary<string, object> result = new Dictionary<string, object>();

            result.Add("rows", new BusinessLogic().SelectByPage<GoodsList>(ref thepage));

            result.Add("total", thepage.SumCount);

 
            //The modified Json() is called
            return Json(result);

        }

}