Santosh Achanta
Oct 5, 2016
  6037
(1 votes)

FormattingJsonAttribute for camel case formatting of variable names and converting enums to strings

I am tired of using JsonProperty decorator for each class member so decided to do something that will automatically take care of camel case conversion of variable names for Json response.

"FormattingJson" is a decorator for a class or a method to convert property names to camel case and enum values to strings whle serializing response object.

Usage: Decorate a class(eg. a API controller) or a method with the below

[FormattingJson(FormatterTypes.CamelCase, FormatterTypes.EnumToString)]

Underlying functions those are respinsible for this utility are CamelCasePropertyNamesContractResolver and StringEnumConverter from Newtonsoft.Json library.

Below is the code for implementation.

using System;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Web.Http.Filters;
using Episerver.Web.Site.Attributes.Formatting.Formatters;

namespace Episerver.Web.Site.Attributes.Formatting
{
    /// <summary>
    /// Apply required formatting on the response content
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public sealed class FormattingJsonAttribute : ActionFilterAttribute
    {
        private readonly FormatterTypes[] _formatterTypes;

        /// <summary>
        /// Initializes a new instance of the <see cref="FormattingJsonAttribute"/> class.
        /// </summary>
        /// <param name="formatterTypes">The formatter types.</param>
        /// <exception cref="System.ArgumentException">At least one formatter type must be provided;formatterTypes</exception>
        public FormattingJsonAttribute(params FormatterTypes[] formatterTypes)
        {
            if (formatterTypes == null || !formatterTypes.Any())
            {
                throw new ArgumentException("At least one formatter type must be provided");
            }

            _formatterTypes = formatterTypes;
        }

        /// <summary>
        /// Occurs after the action method is invoked.
        /// </summary>
        /// <param name="actionExecutedContext">The action executed context.</param>
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            if (actionExecutedContext == null || actionExecutedContext.Response == null)
            {
                return;
            }

            var content = actionExecutedContext.Response.Content as ObjectContent;

            if (content != null)
            {
                var jsonFormatter = new JsonMediaTypeFormatter();
                if (content.Formatter is JsonMediaTypeFormatter)
                {
                    var factory = new FormatterFactory();

                    foreach (var formatter in _formatterTypes)
                    {
                        factory.Create(formatter)
                            .Apply(jsonFormatter);
                    }

                    actionExecutedContext.Response.Content = new ObjectContent(content.ObjectType, content.Value, jsonFormatter);
                }
            }
        }
    }
}

namespace Episerver.Web.Site.Attributes.Formatting
{
    public enum FormatterTypes
    {
        /// <summary>
        /// Changes it from 'CamelCase' to 'camelCase'.
        /// </summary>
        CamelCase = 1,

        /// <summary>
        /// Returns the 'string' version of the enum. The default parsing is 'int'. Example: BalancePosition.Credit will be 'Credit' not '0'
        /// </summary>
        EnumToString = 2
    }
}

using System.Net.Http.Formatting;
using Newtonsoft.Json.Serialization;

namespace Episerver.Web.Site.Attributes.Formatting.Formatters
{
    /// <summary>
    /// Converts output to camel case
    /// </summary>
    public class CamelCaseFormatterApplier : IFormatterApplier
    {
        /// <summary>
        /// Applies the specified formatter.
        /// </summary>
        /// <param name="formatter">The formatter.</param>
        public void Apply(JsonMediaTypeFormatter formatter)
        {
            formatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        }
    }
}

using System.Net.Http.Formatting;
using Newtonsoft.Json.Converters;

namespace Episerver.Web.Site.Attributes.Formatting.Formatters
{
    /// <summary>
    /// Converts enums from int to string
    /// </summary>
    public class EnumStringFormatterApplier : IFormatterApplier
    {
        /// <summary>
        /// Applies the specified formatter.
        /// </summary>
        /// <param name="formatter">The formatter.</param>
        public void Apply(JsonMediaTypeFormatter formatter)
        {
            formatter.SerializerSettings.Converters.Add(new StringEnumConverter());
        }
    }
}

using System.Net.Http.Formatting;

namespace Episerver.Web.Site.Attributes.Formatting.Formatters
{
    /// <summary>
    /// Applies formatting to the response output
    /// </summary>
    public interface IFormatterApplier
    {
        /// <summary>
        /// Applies the specified formatter.
        /// </summary>
        /// <param name="formatter">The formatter.</param>
        void Apply(JsonMediaTypeFormatter formatter);
    }
}

using System;

namespace Episerver.Web.Site.Attributes.Formatting.Formatters
{
    /// <summary>
    /// Creates formatters
    /// </summary>
    public class FormatterFactory
    {
        /// <summary>
        /// Creates the approriate formatter
        /// </summary>
        /// <param name="formatterType"></param>
        /// <returns></returns>
        public IFormatterApplier Create(FormatterTypes formatterType)
        {
            switch (formatterType)
            {
                case FormatterTypes.CamelCase:
                    return new CamelCaseFormatterApplier();

                case FormatterTypes.EnumToString:
                    return new EnumStringFormatterApplier();

                default:
                    throw new ArgumentOutOfRangeException("formatterType", formatterType, "Invalid formatter type");
            }
        }
    }
}
Oct 05, 2016

Comments

Thomas Schmidt
Thomas Schmidt Oct 5, 2016 01:44 PM

I am not entirely sure what you are trying to achieve here, but assuming you just want all json to be serialized with camelCase, then why don't you just set the ContractResolver to CamelCasePropertyNamesContractResolver instead of going whit this attribute approach? One line of code for WebApi configuration and a few lines for Mvc making custom CamelCaseJsonActionResult or similar?

Santosh Achanta
Santosh Achanta Oct 5, 2016 10:21 PM

That's a good point Thomas but I want the formatting/conversion done only if I ask it to do for a method or for the whole controller so went with this Attribute approach.

Please login to comment.
Latest blogs
Creating an Optimizely CMS Addon - Adding an Editor Interface Gadget

In   Part One   of this series, I covered getting started with creating your own AddOn for Optimizely CMS 12. This covered what I consider to be an...

Mark Stott | Aug 30, 2024

Configure your own Search & Navigation timeouts

The main blog Configure your own Search & Navigation timeouts was posted for years but you need copy the code to your application. We now bring tho...

Manh Nguyen | Aug 30, 2024

Joining the Optimizely MVP Program

Andy Blyth has been honoured as an Optimizely MVP, recognising his contributions to the Optimizely community. Learn how this achievement will enhan...

Andy Blyth | Aug 29, 2024 | Syndicated blog

Welcome 2024 Summer OMVPs

Hello, Optimizely community! We are thrilled to announce and welcome the newest members to the Optimizely Most Valuable Professionals (OMVP) progra...

Patrick Lam | Aug 29, 2024

Create custom folder type in Edit Mode

Content Folders, which are located in assets pane gadget or multichannel content gadget, allow you to add any type of block or folders. But...

Grzegorz Wiecheć | Aug 28, 2024 | Syndicated blog

Creating an Optimizely AddOn - Getting Started

When Optimizely CMS 12 was launched in the summer of 2021, I created my first AddOn for Optimizely CMS and talked about some of the lessons I learn...

Mark Stott | Aug 28, 2024