1

I want camel cased JSON on all controller results expect for one specific controller that returns a Dictionary

I tried this

public class PascalCaseConfigAttribute : Attribute, IControllerConfiguration
{
    public void Initialize(HttpControllerSettings config,
                           HttpControllerDescriptor controllerDescriptor)
    {
        var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().Single();
        jsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver();
    }
}

But that changes the global config so after any controller has been called with that attribute we will be back att Pascal case.

How can I fix so taht the default is camel case and explicit fix Paascal case for a certain controller?

edit: This works but feels a bit backward

public class PascalCaseConfigAttribute : Attribute, IControllerConfiguration
{
    public void Initialize(HttpControllerSettings config,
                           HttpControllerDescriptor controllerDescriptor)
    {
        var formatter = config.Formatters.OfType<JsonMediaTypeFormatter>().Single();
        config.Formatters.Remove(formatter);

        formatter = new JsonMediaTypeFormatter();
        formatter.SerializerSettings.ContractResolver = new DefaultContractResolver();

        config.Formatters.Add(formatter);
    }
}
Anders
  • 17,306
  • 10
  • 76
  • 144
  • The first answer on this thread sounds like a reasonable solution: http://stackoverflow.com/questions/12501805/how-to-set-json-net-contractserializer-for-a-certain-specific-type-instead-of-gl – Joanna Derks May 02 '13 at 20:05
  • Yes Im doing his approach above ;) – Anders May 02 '13 at 20:08

1 Answers1

0

Newing up the Json formatter(your second block of code) is best for resolving the problem of not modifying the global formatter state as you have figured + also features like content negotiation, deserialization, help page all consider per-controller configuration too. So having your settings here integrates well with other features too.

Kiran
  • 56,921
  • 15
  • 176
  • 161