Смена сериализатора проста, если вы используете Web API, но, к сожалению, сам MVC использует JavaScriptSerializer
без возможности изменить это значение для использования JSON.Net.
ответ Джеймса и ответ Даниэля дает вам гибкость JSON.Net, но означает, что везде, где вы обычно делаете return Json(obj)
, вы должны перейти на return new JsonNetResult(obj)
или Подобное, которое, если у вас большой проект, может оказаться проблемой, а также не очень гибко, если вы передумаете на сериализаторе, который хотите использовать.
Я решил пойти по маршруту ActionFilter
. Приведенный ниже код позволяет вам выполнять любые действия с использованием JsonResult
и просто применять к нему атрибут для использования JSON.Net (со свойствами нижнего регистра):
[JsonNetFilter]
[HttpPost]
public ActionResult SomeJson()
{
return Json(new { Hello = "world" });
}
// outputs: { "hello": "world" }
Вы даже можете установить это, чтобы автоматически применять ко всем действиям (с незначительным ударом по производительности при проверке is
):
FilterConfig.cs
// ...
filters.Add(new JsonNetFilterAttribute());
код
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);
}
}
}
}