【发布时间】:2012-03-02 03:26:06
【问题描述】:
随着即将到来的WCF Web API,有没有办法控制 JSON 输出?
我想更改大小写,并且可能禁止在序列化类时包含某些属性。
作为一个例子,考虑这个非常简单的类:
[XmlRoot("catalog", Namespace = "http://api.247e.com/catalog/2012")]
public class Catalog
{
[XmlArray(ElementName = "link-templates")]
public LinkTemplate[] LinkTemplates { get; set; }
}
如您所见,我添加了各种 XML 属性来控制它在 XML 中的序列化方式。我可以为 JSON 做同样的事情(或其他事情)吗?
作为参考,以下是 XML 格式的示例输出:
<catalog xmlns="http://api.247e.com/catalog/2012"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<link-templates>
<link-template href="http://localhost:9000/search/?criterion={criterion}"
rel="http://docs.247e.com/rels/search"/>
</link-templates>
</catalog>
对于 JSON,等价的结果是这样的:
{
"LinkTemplates":
[
{
"Href":"http:\/\/localhost:9000\/search\/?criterion={criterion}",
"Rel":"http:\/\/docs.247e.com\/rels\/search"
}
]
}
但是,我想更改属性的大小写,所以我更喜欢这样的东西:
{
"linkTemplates":
[
{
"href":"http:\/\/localhost:9000\/search\/?criterion={criterion}",
"rel":"http:\/\/docs.247e.com\/rels\/search"
}
]
}
剥离某些类属性的方法也不错。
【问题讨论】:
标签: .net json rest formatting wcf-web-api