Web API 2 how to return JSON with camelCased property names, on objects and their sub-objects
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
In modern web development, ensuring consistency in data formats is crucial, especially when integrating various components in an application. A common scenario is the return of JSON data from a Web API. By default, .NET's Web API serializes JSON with PascalCased property names, which might not align with the camelCase convention often used in JavaScript. This article explores how to configure Web API 2 to return JSON with camelCased property names for objects and their sub-objects.
Technical Explanation
JSON Serialization in Web API 2
Web API 2 uses the `JsonMediaTypeFormatter` for JSON serialization, which by default relies on `Json.NET` (now `Newtonsoft.Json`). The `Json.NET` library is highly customizable and supports a variety of settings that make it easier to achieve the desired serialization format.
Configuring CamelCasing
To configure the Web API to return JSON with camelCased property names, modify the `JsonSerializerSettings` in your `WebApiConfig` class, typically found in the `App_Start` folder of an ASP.NET project. Here's how you can do that:
- CamelCasePropertyNamesContractResolver: This is a contract resolver provided by `Json.NET` that modifies the serialization process to output property names in camelCase.
- Removing XmlFormatter: To ensure JSON is always used as the response format, the XML formatter can be removed entirely.
- JavaScript Interoperability: JavaScript typically uses camelCase convention, so aligning JSON properties with this convention reduces confusion and potential bugs.
- Consistency: Maintains naming consistency across different layers of the application.
- Global Configuration: By setting the camel case contract resolver globally in `WebApiConfig`, you ensure the naming convention is consistently applied throughout the API.
- Versioning Considerations: If your API has multiple versions, consider applying this setting in a version-specific configuration to avoid breaking changes for existing clients.
- Customization: Beyond just camel casing, `Json.NET` allows further customization of the serialization process, such as ignoring specific properties or changing date formats.

