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.
Sample 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
}
Answer : Yes
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; }
}
Source from :
http://stackoverflow.com/questions/14298968/is-there-a-way-to-alias-response-model-properties-in-asp-net-web-api
http://www.ryanvice.net/uncategorized/extending-json-net-to-serialize-json-properties-using-a-format-that-is-delimited-by-dashes-and-all-lower-case/
Comments
Post a Comment