Alex Rivera | Logout

Is there a way to alias response model properties in ASP.Net Web API

Asked 2013-01-12T23:18:07.093
28

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
    }
Edit
Report

1 Answer

55

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; }   
    }
answered 2013-01-12T23:37:36.137

Your Answer