La modifica del serializzatore è semplice se si utilizza l'API Web, ma sfortunatamente lo stesso MVC non utilizza JavaScriptSerializeralcuna opzione per modificarlo per utilizzare JSON.Net.
La risposta di James e la risposta di Daniel ti danno la flessibilità di JSON.Net ma significa che ovunque tu faresti normalmente return Json(obj)devi cambiare return new JsonNetResult(obj)o qualcosa di simile che se hai un grande progetto potrebbe rivelarsi un problema, e inoltre non è molto flessibile se cambi idea sul serializzatore che desideri utilizzare.
Ho deciso di seguire la ActionFilterstrada. Il codice seguente ti consente di eseguire qualsiasi azione utilizzando JsonResulte semplicemente applicare un attributo ad esso per utilizzare JSON.Net (con proprietà minuscole):
[JsonNetFilter]
[HttpPost]
public ActionResult SomeJson()
{
return Json(new { Hello = "world" });
}
Puoi anche impostarlo in modo che si applichi automaticamente a tutte le azioni (con solo la minima prestazione di un isassegno):
FilterConfig.cs
filters.Add(new JsonNetFilterAttribute());
Il codice
public class JsonNetFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.Result is JsonResult == false)
return;
filterContext.Result = new CustomJsonResult((JsonResult)filterContext.Result);
}
private class CustomJsonResult : JsonResult
{
public CustomJsonResult(JsonResult jsonResult)
{
this.ContentEncoding = jsonResult.ContentEncoding;
this.ContentType = jsonResult.ContentType;
this.Data = jsonResult.Data;
this.JsonRequestBehavior = jsonResult.JsonRequestBehavior;
this.MaxJsonLength = jsonResult.MaxJsonLength;
this.RecursionLimit = jsonResult.RecursionLimit;
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet
&& String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException("GET not allowed! Change JsonRequestBehavior to AllowGet.");
var response = context.HttpContext.Response;
response.ContentType = String.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;
if (this.ContentEncoding != null)
response.ContentEncoding = this.ContentEncoding;
if (this.Data != null)
{
var json = JsonConvert.SerializeObject(
this.Data,
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
response.Write(json);
}
}
}
}