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 }
return new JsonCamelCaseResult { Data = new Dog { Name = "Rambo", Age = 5 }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
Good solution. I used it in my new framework:
https://github.com/hikalkan/aspnetboilerplate/blob/master/src/Abp/Framework/Abp.Web.Mvc/Controllers/Results/AbpJsonResult.cs
Thanks.
Thank you. Really helpful even though it is an old article.