MVC에서 JSON Serialize는 JavaScriptSerializer를 사용하도록 되어 있습니다.
그런데 다들 아시다시피 JavaScriptSerializer보다 Json.net의 성능이 좋다고 알려져 있습니다.
그래서 MVC에서 기본적으로 Json을 리턴해 줄 때 Json.net을 기본으로 사용할 수 있을까 싶어 찾아보았습니다. 아래 url에서 확인한 내용을 토대로 설명드립니다.
1. Json.net으로 Serialize 해주는 Mapping class을 만들어 줍니다.
public class JsonNetResult : JsonResult
{
public JsonSerializerSettings Settings { get; private set; }
public JsonNetResult()
{
Settings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Error,
};
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentException("context");
if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET",
StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException("JSON GET is not allowed");
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = string.IsNullOrWhiteSpace(this.ContentType) ? "application/json" : this.ContentType;
if (this.ContentEncoding != null)
response.ContentEncoding = this.ContentEncoding;
if (this.Data == null)
return;
var scriptSerializer = JsonSerializer.Create(this.Settings);
using (var sw = new StringWriter())
{
scriptSerializer.Serialize(sw, this.Data);
response.Write(sw.ToString());
}
}
}
2. BaseController에 Json함수를 override 합니다.
protected override JsonResult Json(object data, string contentType,
Encoding contentEncoding, JsonRequestBehavior behavior)
{
return new JsonNetResult
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior
};
}
반응형
'Language > C#' 카테고리의 다른 글
| [ASP.NET MVC] Complie-Time에 View 에러 확인 (0) | 2013.12.20 |
|---|---|
| HTTP 인증(1) - Basic (0) | 2013.09.04 |
| HttpClient (0) | 2013.06.29 |
| 날짜 형식 찾기 위한 정규식 (1) | 2010.04.13 |