Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use camel case serialization only for specific actions

I've used WebAPI for a while, and generally set it to use camel case json serialization, which is now rather common and well documented everywhere.

Recently however, working on a much larger project, I came across a more specific requirement: we need to use camel case json serialization, but because of backward compatibility issues with our client scripts, I only want it to happen for specific actions, to avoid breaking other parts of the (extremely large) website.

I figure one option is to have a custom content type, but that then requires client code to specify it.

Is there any other option?

Thanks!

like image 610
Francois Ward Avatar asked Jan 25 '13 19:01

Francois Ward


1 Answers

Try this:

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

    public CamelCasingFilterAttribute()
    {
        _camelCasingFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    }

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

Apply this [CamelCasingFilter] attribute to any action you want to camel-case. It will take any JSON response you were about to send back and convert it to use camel casing for the property names instead.

like image 150
Youssef Moussaoui Avatar answered Oct 11 '22 15:10

Youssef Moussaoui