[英]managing property names returned in json from web api
I am currently working with ASP.NET web api where I return a Model object like following from my REST operation: 我目前正在使用ASP.NET web api,我从REST操作返回一个Model对象,如下所示:
Product with properties: Name, Id, Description, etc.....
带有属性的产品:
Name, Id, Description, etc.....
When this is converted to a JSON
object, it outputs it with property names above. 当它转换为
JSON
对象时,它将使用上面的属性名称输出它。
To cut down the payload returned from the web api operation, is there any way I can change the properties in the JSON object like for example Desc
for Description
. 为了减少从web api操作返回的有效负载,我有什么方法可以更改JSON对象中的属性,例如
Desc
for Description
。 I could change the Model object but the property names would not make sense then! 我可以更改Model对象,但属性名称没有意义!
The easy way to do this is through a data contract. 这样做的简单方法是通过数据合同。 Here is an article , but basically, it involves two annotations on your model.
这是一篇文章 ,但基本上,它涉及模型上的两个注释。 It also allows you to ignore anything you don't want serialized.
它还允许您忽略任何不想序列化的内容。
[DataContract]
public class Foo { //Your model class
[DataMember(Name="bar-none")] //This also allows you to use chars like '-'
public string bar {get; set;}
[IgnoreDataMember] //Don't serialize this one
public List<string> fuzz { get; set;}
}
You could also consider using http://automapper.org/ on the asp.net side to map your full objects, to more lightweight ones. 您还可以考虑在asp.net端使用http://automapper.org/将您的完整对象映射到更轻量级的对象。 Might be overkill for just one or two small objects, but if you have a bunch to do this can save you some time (free and open source to boot).
对于一个或两个小物件可能有点过分,但如果你有一堆这样做可以节省你一些时间(免费和开源的开机)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.