Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

My problem is that I wish to return camelCased (as opposed to the standard PascalCase) JSON data via ActionResults from ASP.NET MVC controller methods, serialized by JSON.NET.

As an example consider the following C# class:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

By default, when returning an instance of this class from an MVC controller as JSON, it'll be serialized in the following fashion:

{
  "FirstName": "Joe",
  "LastName": "Public"
}

I would like it to be serialized (by JSON.NET) as:

{
  "firstName": "Joe",
  "lastName": "Public"
}

How do I do this?

share|improve this question

4 Answers 4

up vote 21 down vote accepted

I found an excellent solution to this problem on Mats Karlsson's blog. The solution is to write a subclass of ActionResult that serializes data via JSON.NET, configuring the latter to follow the camelCase convention:

public class JsonCamelCaseResult : ActionResult
{
    public JsonCamelCaseResult(object data, JsonRequestBehavior jsonRequestBehavior)
    {
        Data = data;
        JsonRequestBehavior = jsonRequestBehavior;
    }

    public Encoding ContentEncoding { get; set; }

    public string ContentType { get; set; }

    public object Data { get; set; }

    public JsonRequestBehavior JsonRequestBehavior { get; set; }

    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("This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.");
        }

        var response = context.HttpContext.Response;

        response.ContentType = !String.IsNullOrEmpty(ContentType) ? ContentType : "application/json";
        if (ContentEncoding != null)
        {
            response.ContentEncoding = ContentEncoding;
        }
        if (Data == null)
            return;

        var jsonSerializerSettings = new JsonSerializerSettings
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        };
        response.Write(JsonConvert.SerializeObject(Data, jsonSerializerSettings));
    }
}

Then use this class as follows in your MVC controller method:

public ActionResult GetPerson()
{
    return new JsonCamelCaseResult(new Person { FirstName = "Joe", LastName = "Public" }, JsonRequestBehavior.AllowGet)};
}
share|improve this answer
1  
Perfect answer: clean and reusable! Thank you. –  sander Mar 4 at 20:45

or, simply put:

JsonConvert.SerializeObject(
    <YOUR OBJECT>, 
    new JsonSerializerSettings 
    { 
        ContractResolver = new CamelCasePropertyNamesContractResolver() 
    });

For instance:

return new ContentResult
            {
                ContentType = "text/plain",
                Content = JsonConvert.SerializeObject(new { content = result, rows = dto }, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }),
                ContentEncoding = Encoding.UTF8
            };
share|improve this answer
    
This is more complex to use though, since you must configure a ContentResult for each controller method. –  aknuds1 Mar 18 '14 at 15:11
1  
Yeah I understand that your answer was a reusable solution, my point is to make it more clear that it is only a parameter on the Serialize method. –  WebDever Mar 18 '14 at 21:00
    
No, that's missing out on the big picture, which is to return camelCased data from controller methods. –  aknuds1 Mar 18 '14 at 21:50

Below is an action method that returns a json string (cameCase) by serializing an array of objects.

public string GetSerializedCourseVms()
    {
        var courses = new[]
        {
            new CourseVm{Number = "CREA101", Name = "Care of Magical Creatures", Instructor ="Rubeus Hagrid"},
            new CourseVm{Number = "DARK502", Name = "Defence against dark arts", Instructor ="Severus Snape"},
            new CourseVm{Number = "TRAN201", Name = "Transfiguration", Instructor ="Minerva McGonal"}
        };
        var camelCaseFormatter = new JsonSerializerSettings();
        camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver();
        return JsonConvert.SerializeObject(courses, camelCaseFormatter);
    }

Note the JsonSerializerSettings instance passed as the second parameter. That's what makes the camelCase happen.

share|improve this answer

For WebAPI, check out this link: http://odetocode.com/blogs/scott/archive/2013/03/25/asp-net-webapi-tip-3-camelcasing-json.aspx

Basically, add this code to your Application_Start:

var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
share|improve this answer
1  
This does not answer the question, which is about ASP.NET MVC controllers, not Web API. –  aknuds1 Feb 5 at 8:39
1  
You could post a corresponding question on ASP.NET Web API if there isn't one already, and add your answer to that instead. –  aknuds1 Feb 5 at 9:09
    
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. –  Stephen Byrne Feb 5 at 14:26
    
Giving me a -1 for this is answer very rude Mr. @aknuds1 as my answer is obviously related to the subject and I started by stating this is for WebAPI. But hey - whatever makes you happy. –  Assaf S. Feb 8 at 8:36
    
Your answer does not answer the question, it not being about Web API, so it can only confuse. It has nothing to do with being rude or polite. I also explained what would be the right approach. –  aknuds1 Feb 8 at 11:25

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.