Zmiana serializatora jest prosta, jeśli używasz interfejsu API sieci Web, ale niestety samo MVC używa JavaScriptSerializerbez opcji zmiany tego, aby używać JSON.Net.
Odpowiedź Jamesa i odpowiedź Daniela zapewniają elastyczność JSON.Net, ale oznaczają, że wszędzie tam, gdzie normalnie byś to zrobił return Json(obj), musisz zmienić na return new JsonNetResult(obj)lub coś podobnego, co w przypadku dużego projektu może okazać się problemem, a także nie jest zbyt elastyczne, jeśli zmienisz zdanie na temat serializatora, którego chcesz użyć.
Postanowiłem pójść tą ActionFiltertrasą. Poniższy kod umożliwia wykonanie dowolnej akcji przy użyciu JsonResulti po prostu zastosowanie do niego atrybutu, aby użyć JSON.Net (z właściwościami małych liter):
[JsonNetFilter]
[HttpPost]
public ActionResult SomeJson()
{
return Json(new { Hello = "world" });
}
Możesz nawet ustawić to tak, aby automagicznie stosowało się do wszystkich akcji (z tylko niewielkim uderzeniem wydajnościowym podczas isczeku):
FilterConfig.cs
filters.Add(new JsonNetFilterAttribute());
Kod
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);
}
}
}
}