Skip to content

Instantly share code, notes, and snippets.

@DavidDeSloovere
Created June 1, 2013 09:39
Show Gist options
  • Save DavidDeSloovere/5689824 to your computer and use it in GitHub Desktop.
Save DavidDeSloovere/5689824 to your computer and use it in GitHub Desktop.
JsonNetResult for ASP.NET MVC - correct formatting of dates and camel cased properties Got most of the code from Stack Overflow.
using System;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
public class JsonNetResult : JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
var response = context.HttpContext.Response;
response.ContentType = !string.IsNullOrEmpty(this.ContentType) ? this.ContentType : "application/json";
if (this.ContentEncoding != null)
{
response.ContentEncoding = this.ContentEncoding;
}
if (this.Data == null)
{
return;
}
var jsonSerializerSettings = new JsonSerializerSettings();
jsonSerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
jsonSerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
var formatting = HttpContext.Current != null && HttpContext.Current.IsDebuggingEnabled ? Formatting.Indented : Formatting.None;
var serializedObject = JsonConvert.SerializeObject(Data, formatting, jsonSerializerSettings);
response.Write(serializedObject);
}
}
@D-Bullock
Copy link

How would one use this inside of an action?

@perrytribolet
Copy link

Ricky Wan shows how to incorporate JsonNetResult into your code by overriding the Controller.Json method
http://wingkaiwan.com/2012/12/28/replacing-mvc-javascriptserializer-with-json-net-jsonserializer/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment