Serialize .NET objects as camelCase JSON

By | 2012-06-02

ASP.NET MVC is amazing how easy it is to serialize from a .NET POCO to JSON and the other way around using the model binder. But one thing I really don’t like is how serializing .NET objects to JSON returns the properties PascalCase.

Net has PascalCase coding convention for properties and JavaScript uses camelCase.

The solution is to use Json.NET to serialize the objects (which will be included by default in Visual Studio 2012).

Continuing on the previous blog post you would then

Install Newtonsoft Json.NET using NuGet.

Modify the controller so instead of returning

return Json(new Dog { Name = "Rambo", Age = 5 }, JsonRequestBehavior.AllowGet);

you would create a JsonSerializerSettings, Serialize the object with JsonConvert and return the content with content type application/json

public ActionResult Load()
  var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
  var json = JsonConvert.SerializeObject(dog, Formatting.Indented, jsonSerializerSettings);

  return Content(json, "application/json");

which would give you

  "name": "Rambo",
  "age": 5

instead of

  "Name": "Rambo",
  "Age": 5

Of course you would have to update your bindings and ViewModel-data to use camel case instead of pascal case.

And when sending camelCase JSON to your controller the modelbinder automatically handles it and deserializes it correctly.

I have included a updated example solution from the previous blog post where I have created a JsonCamelCaseResult inherited from ActionResult.


return new JsonCamelCaseResult
                   Data = new Dog { Name = "Rambo", Age = 5 }, 
                   JsonRequestBehavior = JsonRequestBehavior.AllowGet
              }; (465.98 kb)

2 thoughts on “Serialize .NET objects as camelCase JSON

  1. Aravind

    Thank you. Really helpful even though it is an old article.


Leave a Reply to Halil ibrahim Kalkan Cancel reply

Your email address will not be published. Required fields are marked *