有没有办法别名在ASP.Net的Web API响应模特属性 [英] Is there a way to alias response model properties in ASP.Net Web API

查看:345
本文介绍了有没有办法别名在ASP.Net的Web API响应模特属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您想返回从使用JSON风格小写名称网页API操作方法的对象,是有没有办法别名属性名称那么,下面的C#对象看起来像下面的JSON对象。

C#响应模型

公共类帐户
    {
        公众诠释标识{搞定;组; }
        公共字符串帐户名{获得;组; }
        公共小数AccountBalance {搞定;组; }    }

要返回JSON,我想

  {
        ID:12,
        帐户名:主要检查
        账户余额:1000
    }


解决方案

您可以使用JSON.NET的 JsonProperty

公共类帐户
    {
        [JsonProperty(属性名=ID)]
        公众诠释标识{搞定;组; }
        [JsonProperty(属性名=帐户名)]
        公共字符串帐户名{获得;组; }
        [JsonProperty(属性名=账户余额)]
        公共小数AccountBalance {搞定;组; }
    }

这将只与JSON.NET工作 - 显然。如果你想更不可知,而且有这种类型的命名,以便能够其它潜​​在格式化的(即你会改变JSON.NET别的东西,或XML序列化),参考 System.Runtime .Serialization 及用途:

[DataContract]
 公共类帐户
    {
        [数据成员(NAME =ID)]
        公众诠释标识{搞定;组; }
        [数据成员(NAME =帐户名)]
        公共字符串帐户名{获得;组; }
        [数据成员(NAME =账户余额)]
        公共小数AccountBalance {搞定;组; }
    }

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
    }

解决方案

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; }   
    }

这篇关于有没有办法别名在ASP.Net的Web API响应模特属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆