Santosh Achanta
Oct 5, 2016
  6246
(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
Increase timeout for long running SQL queries using SQL addon

Learn how to increase the timeout for long running SQL queries using the SQL addon.

Tomas Hensrud Gulla | Dec 20, 2024 | Syndicated blog

Overriding the help text for the Name property in Optimizely CMS

I recently received a question about how to override the Help text for the built-in Name property in Optimizely CMS, so I decided to document my...

Tomas Hensrud Gulla | Dec 20, 2024 | Syndicated blog

Resize Images on the Fly with Optimizely DXP's New CDN Feature

With the latest release, you can now resize images on demand using the Content Delivery Network (CDN). This means no more storing multiple versions...

Satata Satez | Dec 19, 2024

Simplify Optimizely CMS Configuration with JSON Schema

Optimizely CMS is a powerful and versatile platform for content management, offering extensive configuration options that allow developers to...

Hieu Nguyen | Dec 19, 2024