115

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.

Nerdroid
  • 13,398
  • 5
  • 58
  • 69
Tom
  • 7,994
  • 8
  • 45
  • 62
  • http://www.matskarlsson.se/blog/serialize-net-objects-as-camelcase-json – Aron Feb 17 '15 at 00:47
  • Also there is a reason why Linq2SQL produces partial classes. Also...Linq2SQL WTF?! – Aron Feb 17 '15 at 00:48
  • 1
    Thanks but this link is for MVC, it's Web API 2 I'm using, and I'm not sure if there's a way to set the content-type like this, and return a string, but if there is it doesn't seem like quite the right solution.. Thanks for the tip about partial classes too, but is it possible to add an attribute to a property defined in the other part of the partial? – Tom Feb 17 '15 at 00:58
  • Also yes, linq2sql wtf... not my decision :) – Tom Feb 17 '15 at 00:58
  • the result is the same, the only difference is where you inject the `JsonSerializer`. http://stackoverflow.com/questions/13274625/how-to-set-custom-jsonserializersettings-for-json-net-in-mvc-4-web-api – Aron Feb 17 '15 at 01:53
  • yes it is possible, but not in C#. You'd probably want to achieve it using some sort of compile time AOP like PostSharp or Fody. – Aron Feb 17 '15 at 01:57

9 Answers9

183

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;
}
benPearce
  • 37,735
  • 14
  • 62
  • 96
Aron
  • 15,464
  • 3
  • 31
  • 64
  • Definitely the way to turn it on, but my problem was that this setting was being ignored (see my answer) – Tom Feb 17 '15 at 04:30
  • 1
    @Tom erm...Tom did you know what `json.UseDataContractJsonSerializer = true;` does? It tells WebAPI not to use `Json.Net` for serialization. >_ – Aron Feb 17 '15 at 05:52
  • Yes, I do now. However, there was also an additional problem. I verified this. See my answer. Also see http://stackoverflow.com/questions/28552567/web-api-2-how-to-return-json-with-camelcased-property-names-on-objects-and-the/28553295#28553295 – Tom Feb 17 '15 at 06:10
  • 1
    In fact, on closer inspection it turns out that I was mistaken in my earlier conclusion. See my update. – Tom Feb 17 '15 at 08:05
31

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.

felix-b
  • 8,178
  • 1
  • 26
  • 36
  • 3
    This approach is very useful when one wants to have the camelCasing only for some APIs, not for all the APIs in the application. (Y) – droidbot Apr 21 '16 at 14:03
16

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.

Tom
  • 7,994
  • 8
  • 45
  • 62
  • This is actually the wrong answer. See my update in the question. – Tom Feb 17 '15 at 08:00
  • I actually found this to be the case. When returning `Json(result)`, I was seeing everything in PascalCase, but when I returned `Content(StatusCode, result)` it worked as expected. – DeeKayy90 Dec 04 '17 at 06:58
14

All the above answers didn't work for me with Owin Hosting and Ninject. Here's what worked for me:

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        // Get the ninject kernel from our IoC.
        var kernel = IoC.GetKernel();

        var config = new HttpConfiguration();

        // More config settings and OWIN middleware goes here.

        // Configure camel case json results.
        ConfigureCamelCase(config);

        // Use ninject middleware.
        app.UseNinjectMiddleware(() => kernel);

        // Use ninject web api.
        app.UseNinjectWebApi(config);
    }

    /// <summary>
    /// Configure all JSON responses to have camel case property names.
    /// </summary>
    private void ConfigureCamelCase(HttpConfiguration config)
    {
        var jsonFormatter = config.Formatters.JsonFormatter;
        // This next line is not required for it to work, but here for completeness - ignore data contracts.
        jsonFormatter.UseDataContractJsonSerializer = false;
        var settings = jsonFormatter.SerializerSettings;
#if DEBUG
        // Pretty json for developers.
        settings.Formatting = Formatting.Indented;
#else
        settings.Formatting = Formatting.None;
#endif
        settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    }
}

The key difference is: new HttpConfiguration() rather than GlobalConfiguration.Configuration.

mkaj
  • 3,421
  • 1
  • 31
  • 23
14

Code of WebApiConfig:

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
    
            // Web API routes
            config.MapHttpAttributeRoutes();
    
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
    
            //This line sets json serializer's ContractResolver to CamelCasePropertyNamesContractResolver, 
            //  so API will return json using camel case
            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    
        }
    }

Make sure your API Action Method returns data in following way and you have installed latest version of Json.Net/Newtonsoft.Json Installed:
    [HttpGet]
    public HttpResponseMessage List()
    {
        try
        {
            var result = /*write code to fetch your result - type can be anything*/;
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }
        catch (Exception ex)
        {
            return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
        }
    }
Jay Shah
  • 3,553
  • 1
  • 27
  • 26
  • In 2023 using .NET Framework 4.7.2 with WebAPI 2 (with all up-to-date nuggets) the config.Formatters.JsonFormatter line is all I needed to do to convert everything to camelCase (even Swagger OpenAPI figured out the camel case configuration automatically). Thank you! – timmi4sa Apr 06 '23 at 22:35
4

In your Owin Startup add this line...

 public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var webApiConfiguration = ConfigureWebApi();            
        app.UseWebApi(webApiConfiguration);
    }

    private HttpConfiguration ConfigureWebApi()
    {
        var config = new HttpConfiguration();

        // ADD THIS LINE HERE AND DONE
        config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); 

        config.MapHttpAttributeRoutes();
        return config;
    }
}
smatthews1999
  • 156
  • 11
3

Here's an obscure one, when the route attribute did not match the GET url but the GET url matched the method name, the jsonserializer camel case directive would be ignored e.g.

http://website/api/geo/geodata

//uppercase fail cakes
[HttpGet]
[Route("countries")]
public async Task<GeoData> GeoData()
{
    return await geoService.GetGeoData();
}

//lowercase nomnomnom cakes
[HttpGet]
[Route("geodata")]
public async Task<GeoData> GeoData()
{
    return await geoService.GetGeoData();
}
jenson-button-event
  • 18,101
  • 11
  • 89
  • 155
2

I have solved it following ways.

[AllowAnonymous]
[HttpGet()]
public HttpResponseMessage GetAllItems(int moduleId)
{
    HttpConfiguration config = new HttpConfiguration();
            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;

            try
            {
                List<ItemInfo> itemList = GetItemsFromDatabase(moduleId);
                return Request.CreateResponse(HttpStatusCode.OK, itemList, config);
            }
            catch (System.Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
}
Khademul Basher
  • 127
  • 1
  • 2
1

I'm using WebApi with Breeze and I ran the same issue when trying to execute a non-breeze action into a breeze controller. I tried to use the apprach Request.GetConfiguration but the same result. So, when I access the object returned by Request.GetConfiguration I realize that the serializer used by request is the one that breeze-server use to make it's magic. Any way, I resolved my issue creating a different HttpConfiguration:

public static HttpConfiguration BreezeControllerCamelCase
        {
            get
            {
                var config = new HttpConfiguration();
                var jsonSerializerSettings = config.Formatters.JsonFormatter.SerializerSettings;
                jsonSerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                jsonSerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;

                return config;
            }
        }

and passing it as parameter at Request.CreateResponse as follow:

return this.Request.CreateResponse(HttpStatusCode.OK, result, WebApiHelper.BreezeControllerCamelCase);