If you want to return objects from action methods in Web Api with JSON style lowercase names, is there a way to alias the property names so that the C# object below looks like the JSON object that follows.
C# Response Model
public class Account { public int Id { get; set; } public string AccountName { get; set; } public decimal AccountBalance { get; set; } }
JSON that I'd like to be returned
{ "id" : 12, "account-name" : "Primary Checking", "account-balance" : 1000 }
An alias name for an action method is provided by using ActionName attribute. Also it is necessary to change the route template in the WebApiConfig. cs.
Routing is how Web API matches a URI to an action. Web API 2 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API.
You can use JSON.NET's JsonProperty
public class Account { [JsonProperty(PropertyName="id")] public int Id { get; set; } [JsonProperty(PropertyName="account-name")] public string AccountName { get; set; } [JsonProperty(PropertyName="account-balance")] public decimal AccountBalance { get; set; } }
This will only work with JSON.NET - obviously. If you want to be more agnostic, and have this type of naming to be able to other potential formatters (i.e. you'd change JSON.NET to something else, or for XML serialization), reference System.Runtime.Serialization
and use:
[DataContract] public class Account { [DataMember(Name="id")] public int Id { get; set; } [DataMember(Name="account-name")] public string AccountName { get; set; } [DataMember(Name="account-balance")] public decimal AccountBalance { get; set; } }
Filip's answer above is great if you need granular control over serialization but if you want to make a global change you can do it with a one liner like shown below.
public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter()); config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // This line will cause camel casing to happen by default. } }
http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization#json_camelcasing
Edit Based on the comments below I went ahead and added a blog post with the complete solution here: http://www.ryanvice.net/uncategorized/extending-json-net-to-serialize-json-properties-using-a-format-that-is-delimited-by-dashes-and-all-lower-case/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With