Custom ASP. net mvc JsonResult serialization result
Custom ASP. net mvc controller and JsonResult class
Recently, the front-end page of the Project was developed using the jQuery plug-in of EasyUI. The Datebox component in EasyUI Form was bound to ASP.. net mvc returns a DateTime type data error because ASP. the value in the result of the DateTime type JsonResult returned by. net mvc is"\/Date (277630788015 )\/",Therefore, EasyUI displays the returned value without converting the date and directly displaying it in the DateBox component. There are two solutions to this problem:
- The parser function of the datebox component that extends EasyUI can customize the format of the date. However, a problem is that if you use form. load data first assigns the value to datebox and does not call the parser method of datebox. Only after the form is loaded, the datebox value is changed to the value in the format of "2011-11-3;
- The second method is to modify the Json serialization method of ASP. net mvc, that is, to modify the serialization method of JsonResult. The following describes this method in detail.
First, let's take a look at the source code of the Controller Json method 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 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
}
}
}
}
We should clarify the modification target here. Right, it is the ExecuteResult method. This method serializes the Data object in Json format. You can see that ASP. net mvc uses System. web. script. serialization. javaScriptSerializer class
Now that the goal is clearly defined, let's get started.
1. Extend the JsonResult class to customize a CustomJsonResult class. The code for rewriting the ExecuteResult method is 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
Response. Write (JsonConvert. SerializeObject (Data ));
# Pragma warning restore 0618
}
}
We use the Newtonsoft. Json. JsonConvert class serialization object as Json. For details about serialization comparison in. NET, refer to: Using JSON as the data exchange format in. NET.
- 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 how we actually use it, because Newtonsoft. json. jsonConvert DateTime type can specify the serialization date type 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 object class as IsoDateTimeConverter. The Code is as follows:
[Field ("P_Date", "update date")]
[JsonConverter (typeof (IsoDateTimeConverter)]
Public DateTime P_Date {get; set ;}
The Controller is inherited from BaseController. The returned result of Action is 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 );
Return Json (result );
}
}