Don't miss out Virtual Happy Hour this Friday (April 26).

Try our conversational search powered by Generative AI!

Santosh Achanta
Oct 5, 2016
  5888
(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
Solving the mystery of high memory usage

Sometimes, my work is easy, the problem could be resolved with one look (when I’m lucky enough to look at where it needs to be looked, just like th...

Quan Mai | Apr 22, 2024 | Syndicated blog

Search & Navigation reporting improvements

From version 16.1.0 there are some updates on the statistics pages: Add pagination to search phrase list Allows choosing a custom date range to get...

Phong | Apr 22, 2024

Optimizely and the never-ending story of the missing globe!

I've worked with Optimizely CMS for 14 years, and there are two things I'm obsessed with: Link validation and the globe that keeps disappearing on...

Tomas Hensrud Gulla | Apr 18, 2024 | Syndicated blog

Visitor Groups Usage Report For Optimizely CMS 12

This add-on offers detailed information on how visitor groups are used and how effective they are within Optimizely CMS. Editors can monitor and...

Adnan Zameer | Apr 18, 2024 | Syndicated blog

Azure AI Language – Abstractive Summarisation in Optimizely CMS

In this article, I show how the abstraction summarisation feature provided by the Azure AI Language platform, can be used within Optimizely CMS to...

Anil Patel | Apr 18, 2024 | Syndicated blog

Fix your Search & Navigation (Find) indexing job, please

Once upon a time, a colleague asked me to look into a customer database with weird spikes in database log usage. (You might start to wonder why I a...

Quan Mai | Apr 17, 2024 | Syndicated blog