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

Tom picture Tom · Feb 17, 2015 · Viewed 89.5k times · Source

UPDATE

Thanks for all the answers. I am on a new project and it looks like I've finally got to the bottom of this: It looks like the following code was in fact to blame:

public static HttpResponseMessage GetHttpSuccessResponse(object response, HttpStatusCode code = HttpStatusCode.OK)
{
    return new HttpResponseMessage()
    {
        StatusCode = code,
        Content = response != null ? new JsonContent(response) : null
    };
}

elsewhere...

public JsonContent(object obj)
{
    var encoded = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore } );
    _value = JObject.Parse(encoded);

    Headers.ContentType = new MediaTypeHeaderValue("application/json");
}

I had overlooked the innocuous looking JsonContent assuming it was WebAPI but no.

This is used everywhere... Can I just be the first to say, wtf? Or perhaps that should be "Why are they doing this?"


original question follows

One would have thought this would be a simple config setting, but it's eluded me for too long now.

I have looked at various solutions and answers:

https://gist.github.com/rdingwall/2012642

doesn't seem to apply to latest WebAPI version...

The following doesn't seem to work - property names are still PascalCased.

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;

json.UseDataContractJsonSerializer = true;
json.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;

json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); 

Mayank's answer here: CamelCase JSON WebAPI Sub-Objects (Nested objects, child objects) seemed like an unsatisfactory but workable answer until I realised these attributes would have to be added to generated code as we are using linq2sql...

Any way to do this automatically? This 'nasty' has plagued me for a long time now.

Answer

Aron picture Aron · Feb 17, 2015

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;
}