14

I would like to return camel-cased JSON data using Web API. I inherited a mess of a project that uses whatever casing the previous programmer felt like using at the moment (seriously! all caps, lowercase, pascal-casing & camel-casing - take your pick!), so I can't use the trick of putting this in the WebApiConfig.cs file because it will break the existing API calls:

// Enforce camel-casing for the JSON objects being returned from API calls.
config.Formatters.OfType<JsonMediaTypeFormatter>().First().SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

So I'm using a custom class that uses the JSON.Net serializer. Here is the code:

using System.Web.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

public class JsonNetApiController : ApiController
{
    public string SerializeToJson(object objectToSerialize)
    {
        var settings = new JsonSerializerSettings
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        };

        if (objectToSerialize != null)
        {
            return JsonConvert.SerializeObject(objectToSerialize, Formatting.None, settings);
        }

        return string.Empty;
    }
}

The problem is that the raw data returned looks like this:

"[{\"average\":54,\"group\":\"P\",\"id\":1,\"name\":\"Accounting\"}]"

As you can see, the backslashes mess things up. Here is how I'm calling using the custom class:

public class Test
{
    public double Average { get; set; }
    public string Group { get; set; }
    public int Id { get; set; }
    public string Name { get; set; }
}

public class SomeController : JsonNetApiController
{
    public HttpResponseMessage Get()

    var responseMessage = new List<Test>
    {
        new Test
        {
            Id = 1,
            Name = "Accounting",
            Average = 54,
            Group = "P",
        }
    };

    return Request.CreateResponse(HttpStatusCode.OK, SerializeToJson(responseMessage), JsonMediaTypeFormatter.DefaultMediaType);

}

What can I do differently to get rid of the backslashes? Is there an alternative way to enforcing camel-casing?

dbc
  • 104,963
  • 20
  • 228
  • 340
Halcyon
  • 14,631
  • 17
  • 68
  • 99
  • 1
    are you looking to have camel casing on a per-controller basis without disturbing the global json formatter setting? if yes, then there is a way to do it in Web API – Kiran May 06 '14 at 21:40
  • [Force CamalCase on ASP.NET WebAPI Per Controller](http://stackoverflow.com/questions/19956838/force-camalcase-on-asp-net-webapi-per-controller) – Jeremy Cook May 06 '14 at 21:41
  • @Halcyon: Can you post the "answer" portion of your question as an answer? – StriplingWarrior May 06 '14 at 23:18

3 Answers3

18

Thanks to all the references to other Stackoverflow pages, I'm going to post three solutions so anyone else having a similar issue can take their pick of the code. The first code example is one that I created after looking at what other people were doing. The last two are from other Stackoverflow users. I hope this helps someone else!

// Solution #1 - This is my solution. It updates the JsonMediaTypeFormatter whenever a response is sent to the API call.
// If you ever need to keep the controller methods untouched, this could be a solution for you.
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Web.Http;
using Newtonsoft.Json.Serialization;

public class CamelCasedApiController : ApiController
{
    public HttpResponseMessage CreateResponse(object responseMessageContent)
    {
        try
        {
            var httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK, responseMessageContent, JsonMediaTypeFormatter.DefaultMediaType);
            var objectContent = httpResponseMessage.Content as ObjectContent;

            if (objectContent != null)
            {
                var jsonMediaTypeFormatter = new JsonMediaTypeFormatter
                {
                    SerializerSettings =
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver()
                    }
                };

                httpResponseMessage.Content = new ObjectContent(objectContent.ObjectType, objectContent.Value, jsonMediaTypeFormatter);
            }

            return httpResponseMessage;
        }
        catch (Exception exception)
        {
            return Request.CreateResponse(HttpStatusCode.InternalServerError, exception.Message);
        }
    }
}

The second solution uses an attribute to decorate the API controller method.

// http://stackoverflow.com/questions/14528779/use-camel-case-serialization-only-for-specific-actions
// This code allows the controller method to be decorated to use camel-casing. If you can modify the controller methods, use this approach.
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Web.Http.Filters;
using Newtonsoft.Json.Serialization;

public class CamelCasedApiMethodAttribute : ActionFilterAttribute
{
    private static JsonMediaTypeFormatter _camelCasingFormatter = new JsonMediaTypeFormatter();

    static CamelCasedApiMethodAttribute()
    {
        _camelCasingFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    }

    public override void OnActionExecuted(HttpActionExecutedContext httpActionExecutedContext)
    {
        var objectContent = httpActionExecutedContext.Response.Content as ObjectContent;
        if (objectContent != null)
        {
            if (objectContent.Formatter is JsonMediaTypeFormatter)
            {
                httpActionExecutedContext.Response.Content = new ObjectContent(objectContent.ObjectType, objectContent.Value, _camelCasingFormatter);
            }
        }
    }
}

// Here is an example of how to use it.
[CamelCasedApiMethod]
public HttpResponseMessage Get()
{
    ...
}

The last solution uses an attribute to decorate the entire API controller.

// http://stackoverflow.com/questions/19956838/force-camalcase-on-asp-net-webapi-per-controller
// This code allows the entire controller to be decorated to use camel-casing. If you can modify the entire controller, use this approach.
using System;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Http.Controllers;
using Newtonsoft.Json.Serialization;

public class CamelCasedApiControllerAttribute : Attribute, IControllerConfiguration
{
    public void Initialize(HttpControllerSettings httpControllerSettings, HttpControllerDescriptor httpControllerDescriptor)
    {
        var jsonMediaTypeFormatter = httpControllerSettings.Formatters.OfType<JsonMediaTypeFormatter>().Single();
        httpControllerSettings.Formatters.Remove(jsonMediaTypeFormatter);

        jsonMediaTypeFormatter = new JsonMediaTypeFormatter
        {
            SerializerSettings =
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            }
        };

        httpControllerSettings.Formatters.Add(jsonMediaTypeFormatter);
    }
}

// Here is an example of how to use it.
[CamelCasedApiController]
public class SomeController : ApiController
{
    ...
}
Halcyon
  • 14,631
  • 17
  • 68
  • 99
  • One small tweak I would suggest. I believe the first formatter in the list becomes the default format if no accept type is sent, so this approach can switch your default to xml, which I discovered when testing my api with a REST test tool. Changing the httpControllerSettings.Formatters.Add line to Insert with an index of 0 keeps it first in the list. – Ted Elliott Apr 09 '15 at 20:35
  • @TedElliott this could be because you're not passing along the `Accept-Type` header (with a value of `application/json`). I'd have to test it, but I'm pretty sure WebAPI will return the type you request and if you don't specify, it will use the first one in the list. – Peter May 22 '17 at 07:05
  • CamelCasedApiControllerAttribute did not work for me. But I used CamelCasedApiMethodAttribute and applied it to the controller and it works for all actions. – duyn9uyen Jun 14 '17 at 19:10
1

If you want to set it globally you can just remove the current Json formatter from the HttpConfiguration and replace it with your own.

public static void Register(HttpConfiguration config)
{
    config.Formatters.Remove(config.Formatters.JsonFormatter);

    var serializer = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
    var formatter = new JsonMediaTypeFormatter { Indent = true, SerializerSettings =  serializer };
    config.Formatters.Add(formatter);
}
Jakub Konecki
  • 45,581
  • 7
  • 87
  • 126
Rikard
  • 3,828
  • 1
  • 24
  • 39
  • The existing API end points were being consumed by mobile devices on production, so I couldn't use a global solution. I had to find a workaround for new endpoints. – Halcyon Nov 05 '14 at 19:26
0

Comment on https://stackoverflow.com/a/26506573/887092 works for some cases but not others

var jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;

This way works in other cases

var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();

So, cover all bases with:

    private void ConfigureWebApi(HttpConfiguration config)
    {
        //..

        foreach (var jsonFormatter in config.Formatters.OfType<JsonMediaTypeFormatter>())
        {
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        }

        var singlejsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
        singlejsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

    }
Community
  • 1
  • 1
Kind Contributor
  • 17,547
  • 6
  • 53
  • 70