Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Nathan Reece 62 posts 376 karma points
    Mar 31, 2021 @ 10:01
    Nathan Reece
    0

    Umbraco 8 WebAPI return camelCase

    I am working with Umbraco UmbracoApiController and it's really annoying that the data types come back as TitleCase. I would much prefer them to come back as camelCase. Just how I am used to working.

    Does anyone know if there is a way to do that?

    Thanks

  • Kevin Jump 2343 posts 14890 karma points MVP 8x c-trib
    Mar 31, 2021 @ 10:35
    Kevin Jump
    0

    Hi,

    you should add an attribute to the classes/models that you are returning.

    e.g

    [JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
    public class MyViewModel {
       public string Name { get; set; }
    }
    

    this will serialize those classes in camel casing without changing the global default and potentially breaking other code that might rely on it the other way.

  • David Armitage 510 posts 2081 karma points
    Mar 31, 2021 @ 10:45
    David Armitage
    1

    Hi Nathan,

    This is possible. Here is the code...

    Copy this class into your project.

    public class JsonCamelCaseFormatter : Attribute, IControllerConfiguration
        {
            public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)
            {
                var toRemove = controllerSettings.Formatters.Where(t => (t is JsonMediaTypeFormatter) || (t is XmlMediaTypeFormatter)).ToList();
                foreach (var r in toRemove)
                {
                    controllerSettings.Formatters.Remove(r);
                }
    
                var jsonFormatter = new JsonMediaTypeFormatter
                {
                    SerializerSettings =
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver()
                    }
                };
                controllerSettings.Formatters.Add(jsonFormatter);
            }
        }
    

    Then decorate your controller like this.

    [JsonCamelCaseFormatter]
        public class ResidenceApiController : UmbracoApiController
        {
    
        }
    

    That should be it.

    Regards

    David

  • Nathan Reece 62 posts 376 karma points
    Apr 01, 2021 @ 01:23
    Nathan Reece
    0

    Thats Great,

    Thanks Guys.

  • Jesse Andrews 191 posts 716 karma points c-trib
    Apr 06, 2022 @ 16:31
    Jesse Andrews
    0

    For anyone looking to do this for umbraco 9, there is a thread here with a solution.

Please Sign in or register to post replies

Write your reply to:

Draft