【问题标题】:Prevent serialization of null members in DataContractSerializer防止在 DataContractSerializer 中对空成员进行序列化
【发布时间】:2013-07-14 19:12:34
【问题描述】:

让我先说我对 WCF 相当陌生,并且可能在此处使用了错误的术语。我的项目有两个组成部分:

  1. 包含 Attachment、Extension、ReportType1 和 ReportType2 类的 DLL
  2. 如下所述的带有 OperationContract 的 WCF ServiceContract 将其作为 XML 文档反序列化为相关对象,然后将其再次序列化为 JSON 或 XML 返回客户端。

我有一个如下所示的 XML 架构:

<?xml version="1.0" encoding="windows-1252"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
    <xsd:element name="Attachment">
        <xsd:complexType>
            <xsd:all>
                <xsd:element name="Extension" type="Extension" minOccurs="0" />
            </xsd:all>
        </xsd:complexType>
    </xsd:element>
    <xsd:complexType>
        <xsd:sequence name="Extension">
            <xsd:any processContents="skip" />
        </xsd:sequence>
    </xsd:complexType>
</xsd:schema>

按照这个架构,我有一个以下类型的 XML 文档:

<Attachment>
    <Extension>
        <ReportType1>
            <Name>Report Type 1 Example</Name>
        </ReportType1>
    </Extension>
</Attachment>

我在已编译的 DLL 中有以下类:

public class Attachment
{
    public Extension Extension { get; set; }
}

public class Extension
{
    [XmlElement(ElementName = "ReportType1", IsNullable = false)]
    public ReportType1 ReportType1 { get; set; }

    [XmlElement(ElementName = "ReportType2", IsNullable = false)]
    public ReportType2 ReportType2 { get; set; }
}

我的 WCF 服务将 XML 文档反序列化为上述对象,然后通过以下 OperationContract 以 JSON 格式返回:

[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle=WebMessageBodyStyle.WrappedRequest)]
Attachment Search();

实际输出为 JSON

{
    'Attachment': {
        'Extension': {
            'ReportType1': { ... },
            'ReportType2': null
        }
    }
}

实际输出为 XML

<Attachment>
    <Extension>
        <ReportType1>...</ReportType1>
        <ReportType2 i:nil="true"></ReportType2>
    </Extension>
</Attachment>

所需的 JSON 输出

{
    'Attachment': {
        'Extension': {
            'ReportType1': { ... }
        }
    }
}

所需的 XML 输出

<Attachment>
    <Extension>
        <ReportType1>...</ReportType1>
    </Extension>
</Attachment>

DLL 中的类没有DataContract 属性,但在从我的OperationContract 发回时似乎可以很好地序列化,因为我得到了上述结果。

我如何告诉它不要将元素序列化为 JSON/XML,如果它们是 null 而没有能力将 DLL 中的类转换为 DataContract 类?我是否应该从 DLL 继承类,并以某种方式将它们覆盖为DataContract?如果是这样,那么我该如何在基类的现有成员上设置属性呢?

如果需要更多信息,请告诉我,我会尽力提供。

【问题讨论】:

  • 看看 [custom-serialization-with-datacontractserializer](stackoverflow.com/questions/3156312/…) 问候。
  • 我发现 this SO question 可以满足我的要求,但它需要我装饰 DLL 中的类 - 这超出了我的范围。这里的部分问题是无法修改 DLL 中的类。

标签: c# wcf xml-serialization .net-4.5 datacontractserializer


【解决方案1】:

您可以使用模式 ShouldSerialize{PropertyName} 创建一个函数,它告诉 XmlSerializer 是否应该序列化成员。

check this question

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    相关资源
    最近更新 更多