Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Default JSON Serializer Used In ASP MVC3 [duplicate]

I have a controller that is returning large JSON objects to jQuery Flot and I was wondering how easy it would be to replace the default JavaScriptSerializer with something faster like the one from ServiceStack.Text.

It would be good if I could change stuff like this using the DependencyResolver, but I suppose if absolutely everything was resolved this was, it could get pretty slow.

like image 894
Tim Avatar asked Jul 30 '11 12:07

Tim


1 Answers

your best bet is to inherit from JsonResult class and override Execute method like

public class CustomJsonResult: JsonResult
{
    public CustomJsonResult()
    {
       JsonRequestBehavior = JsonRequestBehavior.DenyGet;
    }
    public override void ExecuteResult(ControllerContext context) {
            if (context == null) {
                throw new ArgumentNullException("context");
            }
            if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
                String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) {
                throw new InvalidOperationException(MvcResources.JsonRequest_GetNotAllowed);
            }

            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) {
                CustomJsSerializer serializer = new CustomJsSerializer();
                response.Write(serializer.Serialize(Data));
            }
        }
}

code is taken from JsonResult class of mvc3 and changed this line

JavaScriptSerializer serializer = new JavaScriptSerializer();

to

CustomJsSerializer serializer = new CustomJsSerializer();

you can use this class in action method like

public JsonResult result()
{
    var model = GetModel();
    return new CustomJsonResult{Data = model};
}

Additionally you can override json method of Controller class in your Base controller like

public class BaseController:Controller
{
   protected internal override JsonResult Json(object data)
        {
            return new CustomJsonResult { Data = data };
        }
}

now if you have all your controllers from BaseController then return Json(data) will call your serialization scheme. There are also other overloads of Json method that you may choose to override.

like image 188
Muhammad Adeel Zahid Avatar answered Oct 28 '22 03:10

Muhammad Adeel Zahid