Web API 2: how to return JSON with camelCased property names, on objects and their sub-objects

Putting it all together you get...

protected void Application_Start()
{
    HttpConfiguration config = GlobalConfiguration.Configuration;
    config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;
}

This is what worked for me:

internal static class ViewHelpers
{
    public static JsonSerializerSettings CamelCase
    {
        get
        {
            return new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
        }
    }
}

And then:

[HttpGet]
[Route("api/campaign/list")]
public IHttpActionResult ListExistingCampaigns()
{
    var domainResults = _campaignService.ListExistingCampaigns();
    return Json(domainResults, ViewHelpers.CamelCase);
}

The class CamelCasePropertyNamesContractResolver comes from Newtonsoft.Json.dll in Json.NET library.


It turns out that

return Json(result);

was the culprit, causing the serialization process to ignore the camelcase setting. And that

return Request.CreateResponse(HttpStatusCode.OK, result, Request.GetConfiguration());

was the droid I was looking for.

Also

json.UseDataContractJsonSerializer = true;

Was putting a spanner in the works and turned out to be NOT the droid I was looking for.