2012-02-09 33 views
2

即将推出WCF Web API,有什么方法可以控制JSON输出吗?有什么办法可以通过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" 
    } 
    ] 
} 

一种方法来剥去某些类的属性也将b很好。

回答

2

WCF Web API默认使用DataContractJsonSerializer以JSON格式返回资源。所以你应该使用你的类的DataContract和DataMember属性来形成JSON结果。

[DataContract] 
public class Book 
{ 
    [DataMember(Name = "id")] 
    public int Id { get; set; } 
    [DataMember(Name = "title")] 
    public string Title { get; set; } 
    [DataMember(Name = "author")] 
    public string Author { get; set; } 
    [XmlIgnore] // Don't send this one 
    public string ImageName { get; set; } 
} 
相关问题