Asp.net-Mvc

更改 ASP MVC3 中使用的預設 JSON 序列化程序 [重複]

  • July 30, 2011

我有一個控制器將大型 JSON 對象返回給 jQuery Flot,我想知道用 ServiceStack.Text 中的更快的東西替換預設的 JavaScriptSerializer 是多麼容易。

如果我可以使用 DependencyResolver 更改這樣的東西會很好,但我想如果絕對一切都解決了,它可能會變得很慢。

您最好的選擇是從 JsonResult 類繼承並覆蓋 Execute 方法,例如

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));
           }
       }
}

程式碼取自 mvc3 的 JsonResult 類並更改了這一行

JavaScriptSerializer serializer = new JavaScriptSerializer();

CustomJsSerializer serializer = new CustomJsSerializer();

您可以在操作方法中使用此類,例如

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

此外,您可以在 Base 控制器中覆蓋 Controller 類的 json 方法,例如

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

現在,如果您擁有 BaseController 中的所有控制器,那麼return Json(data)將呼叫您的序列化方案。Json您還可以選擇覆蓋其他方法重載。

引用自:https://stackoverflow.com/questions/6883204