With Web API it’s super easy to return JSON from the server by returning .NET objects. Unfortunately in .NET public properties are PascalCased while in JavaScript properties are camelCased.
I’ve seen several solutions for prerelease versions of the Web API requiring a few pages of code to override the default behavior. I’ve just found a super easy way that I’d like to share with you. In the default template of an ASP.NET MVC Web API project insert this in your RouteConfig.RegisterRoutes or WebApiConfig.Register, whichever receives GlobalConfiguration.Configuration:
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
Oh, and don’t forget to add using Newtonsoft.Json.Serialization; to your using statements.
Hope this helps!
Just found this solution on the ASP.NET site: http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization
LikeLike
Reblogged this on Sutoprise Avenue, A SutoCom Source.
LikeLike
Great Solution!! It works really easy :)
LikeLike
A property like “CRC32” looks like this: “crC32” … pretty ugly :)
LikeLike
I prefer to name it “Crc32” so it would become “crc32”. Unfortunately the older .NET base class libraries are inconsistent with 2-letter acronyms (‘DB’ vs. ‘Db’) and it is also inconsistent with the JavaScript naming conventions I know. E.g. “MyCrc32” would become “myCrc32” and it should be “myCRC32”. I suppose you could have some manual override but I’m not sure if it’s worth the trouble.
LikeLike
This is just what i was looking for. Thanks.
LikeLike
You’re welcome!
LikeLike
thanks a lot for this elegant, easy and simple solution!
LikeLike
Great Solution . But the problem it is working only for the root level element properties , child object properties are still in pascal case. Any generic solutions are highly appreciated
LikeLike