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
    }

2 Answers 2

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; }   
    }
Sign up to request clarification or add additional context in comments.

3 Comments

For users of this solution, be aware that applying [DataContract] to a class requires the [DataMember] attribute on all properties that you want serialized. I.e. if you start from a class with 10 properties that are currenly serialized by default, and add [DataContract] to the class and [DataMember(Name="a-new-name")] to that property, the other 9 properties won't be serialized anymore.
and how do you change Model name (Account , here)?
Does this work in GET api model?
21

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/

2 Comments

While this is a good idea and clearly easier than defining all those attributes, it's not what the OP asked for. It doesn't solve the dash thing.
@Ryan Your link wasn't working, now it is located here: vicesoftware.com/uncategorized/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.