Created
June 1, 2013 09:39
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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/