【问题标题】:Ignore properties of class when using WCF ResponseFormat = WebMessageFormat.Json使用 WCF ResponseFormat = WebMessageFormat.Json 时忽略类的属性
【发布时间】:2011-10-19 11:10:00
【问题描述】:

我将 WCF 用于使用这种格式的 JSON 服务:

[OperationContract]
[ServiceKnownType(typeof(ComplexResult))]
[WebInvoke(
            Method = "GET",
            BodyStyle = WebMessageBodyStyle.Bare,
            ResponseFormat = WebMessageFormat.Json)]
MyClass MyFunction(string myParams);

这很好用,但是它有一个限制。我不能忽略要序列化为 JSON 的类的属性。如果我使用 JavaScriptSerializer 类,那么我可以将 [ScriptIgnore] 属性放在我想忽略的属性上,它们不会在 JSON 中序列化,但这不适用于上述方法。

有没有办法排除使用 ResponseFormat Json 方法序列化为 JSON 的类的属性?

【问题讨论】:

    标签: c# wcf json


    【解决方案1】:

    WCF 默认使用DataContractJsonSerializer 来序列化对象。根据MyClass的定义方式,可以使用不同的属性来防止成员被序列化:

    • 如果 MyClass 没有任何属性(即,它是“POCO”类型),您可以在不想序列化的成员中使用 [IgnoreDataMember] 属性
    • 如果 MyClass 用 [Serializable] 装饰,您可以在这些成员中使用 [NotSerialized] 属性
    • 如果 MyClass 用[DataContract] 装饰,那么您只需要不添加 [DataMember] 到您不想序列化的成员。

    【讨论】:

      猜你喜欢
      • 2011-12-17
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 2010-10-17
      • 2011-10-18
      • 1970-01-01
      • 1970-01-01
      • 2011-07-13
      相关资源
      最近更新 更多