Serialize .NET Objects as JSON Using CamelCase

Whether you’re using MVC or Web Forms, there are numerous occasions when you need to share data from server-side code to client-side code.  Often, that can be achieved with web services but if there’s a certain context when a page is being rendered (ex. logged in user), it might be easier to just drop the data directly into the HTML markup the server is producing.

The standard for converting .NET objects into JSON is Newtonsoft’s Json.NET.  So much so that Microsoft is bundling it with much of it’s web platform.  That’s probably because it’s so easy to use.

return JsonConvert.SerializeObject(data);

There’s just one problem.  Common .NET standard proposes using Pascal casing for property names.  For JavaScript, the preference is to use CamelCase.  Newtonsoft offers a JsonPropertyAttribute that allows you to change the default behavior but if you wanted to bend your Pascal naming to CamelCase, you’d have to tag every property.  Not scaleable.

Newtonsoft already took this into account.  When you call SerializeObject, you can pass in an instance of a JsonSerializerSettings object.  That class has a property ContractResolver which will allow you to customize how the serialization operates.  But there’s already a canned class of a CamelCasePropertyNamesContractResolver.  So I have a standard function I use to do any of my serializations:

    public class Utility
        public static string SerializeObjectToCamelCaseJson(object data)
            return JsonConvert.SerializeObject(data, new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() });

I take it one step further and use .NET ability to write extensions to existing classes:

        public static string ToCamelCaseJson(this object o)
            return Utility.SerializeObjectToCamelCaseJson(o);

So as long as I include the namespace where that extension is defined, I can call that from within the body of, for example, an MVC Razor view.

var foo = @(Model.Foo.ToCamelCaseJson());

It’s basically just as handy as the standard “ToString” function that’s built into every object and can also be overridden.

2 thoughts on “Serialize .NET Objects as JSON Using CamelCase

  1. Pingback: Render Sitecore Rich-Text Fields for Proper Linking - Find Gnosis

Leave a Reply