c# - 防止 DataContractSerializer 中空成员的序列化

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

首先让我说我是 WCF 的新手,并且可能在此处使用了错误的术语。我的项目有两个组成部分:

  1. 包含附件、扩展、ReportType1 和 ReportType2 类的 DLL
  2. WCF ServiceContract 和如下所述的 OperationContract,将 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?如果是这样,那么我如何在基类的现有成员上设置属性?

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

最佳答案

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

check this question

关于c# - 防止 DataContractSerializer 中空成员的序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17679362/

相关文章:

c# - 带有局部 View 的 MVC 提交表单

c# - 使用 WCF(或其他解决方案)保护双工通信的最佳方法

c# - 哪个是更好的做法,类的一个客户端实例或每个方法中的一个?

.net - 如何将匿名类型的对象序列化为 XML?

c# - WCF Web 服务序列化错误 - 返回空值

java - JAXB - 从 Java 对象字段创建嵌套子元素

c# - 我如何在 Crystal 或 rdlc 报告中绑定(bind) c# 的业务对象?

c# - 如何获取字符串中的单词

.net - 禁止使用 TLS session 票证

c# - 从 MVC HttpPost 将错误返回给 jQuery