Let me preface by saying I'm fairly new to WCF, and might be using the wrong terminology throughout here. My project has two components:
- A DLL containing the classes for Attachment, Extension, ReportType1, and ReportType2
- A WCF ServiceContract with an OperationContract as described below that deserializes as XML document into the relevant objects, then serializes it again as either JSON or XML back out to the client.
I have an XML schema that looks like the following:
<?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>
Following this schema, I have an XML document of the following type:
<Attachment>
<Extension>
<ReportType1>
<Name>Report Type 1 Example</Name>
</ReportType1>
</Extension>
</Attachment>
I've got the following classes in a compiled 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; }
}
My WCF service deserializes the XML document into the above objects, and then returns it in JSON format via the following OperationContract:
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle=WebMessageBodyStyle.WrappedRequest)]
Attachment Search();
Actual Output as JSON
{
'Attachment': {
'Extension': {
'ReportType1': { ... },
'ReportType2': null
}
}
}
Actual Output as XML
<Attachment>
<Extension>
<ReportType1>...</ReportType1>
<ReportType2 i:nil="true"></ReportType2>
</Extension>
</Attachment>
Desired Output as JSON
{
'Attachment': {
'Extension': {
'ReportType1': { ... }
}
}
}
Desired Output as XML
<Attachment>
<Extension>
<ReportType1>...</ReportType1>
</Extension>
</Attachment>
The classes from the DLL do not have the DataContract
attribute, but seem to serialize just fine when being sent back from my OperationContract
, as I get the above results.
How can I tell it not to serialize the elements to JSON/XML if they are null without having the ability to turn the classes from the DLL into a DataContract
class? Should I inherit the classes from the DLL, and somehow override them as DataContract
? If so, how could I set attributes on the existing members of the base classes then?
Please let me know if more information is required, and I will do my best to supply it.