【问题标题】:Is there any way to control JSON formatting with the WCF Web API?有没有办法使用 WCF Web API 控制 JSON 格式?
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      尝试使用 codeplex 上 WCF Web API Contrib 项目中的 JSON.NET 格式化程序。此处显示的属性应该可以帮助您https://json.svn.codeplex.com/svn/trunk/Doc/SerializationAttributes.html

      【讨论】:

        【解决方案3】:

        JSON.NET 有几个属性选项可以控制序列化的内容和方式。 http://james.newtonking.com/projects/json/help/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-03-28
          • 2013-05-21
          • 1970-01-01
          • 2015-05-12
          • 1970-01-01
          • 2015-12-10
          相关资源
          最近更新 更多