首先让我说我是 WCF 的新手,并且可能在此处使用了错误的术语。我的项目有两个组成部分:
- 包含附件、扩展、ReportType1 和 ReportType2 类的 DLL
- 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 是否应该序列化该成员。
关于c# - 防止 DataContractSerializer 中空成员的序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17679362/