Customizing ASP.NET MVC to Serialize Json DateTime in a More Natural Way

If you develop with ASP.NET MVC and use the JsonResult in response from an AJAX call, already had the problem that the DateTime is serilized in the format /Date(Ticks)/. this happens because the JsonResult uses JavaScriptSerializer to serialize the object.

You can use the algorithm below to parse correctly:

function parseDateTime(date) {
    var pattern = /Date\(([^)]+)\)/;
    var results = pattern.exec(date);
    return new Date(parseFloat(results[1]));
}

As you can see, parse the date is not so difficult, but worst than this is if you publish your application in a time region different than your customer the JavaScriptSerializer will try to fix the hours.

One more natural way to solve this problem is to serialize the date with JSON format: yyyy-MM-ddTHH:mm:ss. To customize we will use the Newtonsoft.Json.

Let´s create the JsonNetResult.

public class JsonNetResult : JsonResult
{
    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();
        }

        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)
        {
            response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(Data));
        }
    }
}

Next let´s create the BaseController and override the Json method

public abstract class BaseController : Controller
{
    protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
    {
        return new JsonNetResult
        {
            Data = data,
            ContentType = contentType,
            ContentEncoding = contentEncoding,
            JsonRequestBehavior = behavior
        };
    }
}

Now you just need to inherit your controllers with the BaseController and the JsonResult will serialize Json in more natural way.

public class HomeController : BaseController
{
    public ActionResult TestDateTime()
    {
        return Json(new { CreatedDate = new DateTime(2015, 3, 14, 12, 10, 10) }, JsonRequestBehavior.AllowGet);
    }
}

And the Javascript parseDate method will be much simpler:

function parseDateTime(date) {
    return new Date(date);
}

In this post we saw how to customize the Json method to serialize the DateTime in a more natural way, we created an ActionResult called JsonNetResult and a BaseController that we override the Json method.

Anúncios
Customizing ASP.NET MVC to Serialize Json DateTime in a More Natural Way

Deixe um comentário

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logotipo do WordPress.com

Você está comentando utilizando sua conta WordPress.com. Sair /  Alterar )

Foto do Google

Você está comentando utilizando sua conta Google. Sair /  Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair /  Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair /  Alterar )

Conectando a %s