Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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

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
1  
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
1  
If you're returning JSON from a Controller method, you probably should be using an ApiController, in which case this answer works great. – Simon Hartcher Jun 1 '15 at 9:15
1  
@SimonHartcher Consider the scope of the question though, not the general case. – aknuds1 Jun 25 '15 at 6:52
up vote 62 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
2  
Perfect answer: clean and reusable! Thank you. – sander Mar 4 '15 at 20:45

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
5  
This does not answer the question, which is about ASP.NET MVC controllers, not Web API. – aknuds1 Feb 5 '15 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 '15 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 '15 at 14:26
3  
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 '15 at 11:25
1  
Web API and MVC have been merged in ASP.NET 6 – AlexFoxGill Aug 14 '15 at 15:40

I think this is the simple answer you are looking for. It's from Shawn Wildermuth's blog:

// Add MVC services to the services container.
services.AddMvc()
  .AddJsonOptions(opts =>
  {
    opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
  });
share|improve this answer
    
This is for Asp.Net 5. – Erik Hellström Jan 17 at 12:50
1  
My apologies, guys. I read through this posting too quickly. It is for ASP.NET 5. – Quantium Jan 24 at 11:18
6  
Ironically, I came here looking for an answer to the question you answered here, so while it wasn't the answer to the OP's question, it helped me anyway. Thanks! :) – porcus Mar 14 at 20:25
1  
I second what @porcus said! Thanks @Quantium! – Gromer Mar 30 at 20:47
1  
fyi For ASP.NET Core 1.0 it's camel case by default OOTB – Chris Marisic Jul 7 at 13:24

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

An alternative to the custom filter is to create an extension method to serialize any object to JSON.

public static class ObjectExtensions
{
    /// <summary>Serializes the object to a JSON string.</summary>
    /// <returns>A JSON string representation of the object.</returns>
    public static string ToJson(this object value)
    {
        var settings = new JsonSerializerSettings
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver(),
            Converters = new List<JsonConverter> { new StringEnumConverter() }
        };

        return JsonConvert.SerializeObject(value, settings);
    }
}

Then call it when returning from the controller action.

return Content(person.ToJson(), "application/json");
share|improve this answer

In ASP.NET Core MVC.

    public IActionResult Foo()
    {
        var data = GetData();

        var settings = new JsonSerializerSettings 
        { 
            ContractResolver = new CamelCasePropertyNamesContractResolver() 
        });

        return Json(data, settings);
    }
share|improve this answer

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.