Let me introduce the preface by saying that I am fairly new to WCF, and the wrong terminology can be used here. My project consists of two components:
- DLL containing classes for Attachment, Extension, ReportType1 and ReportType2
- The WCF ServiceContract with OperationContract, as described below, is deserialized as an XML document into the appropriate objects, then serializes it again when JSON or XML is returned to the client.
I have an XML schema that looks like this:
<?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 pattern, I have an XML document of the following type:
<Attachment> <Extension> <ReportType1> <Name>Report Type 1 Example</Name> </ReportType1> </Extension> </Attachment>
I have 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 using 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 result as XML
<Attachment> <Extension> <ReportType1>...</ReportType1> <ReportType2 i:nil="true"></ReportType2> </Extension> </Attachment>
Desired result as JSON
{ 'Attachment': { 'Extension': { 'ReportType1': { ... } } } }
Desired result as XML
<Attachment> <Extension> <ReportType1>...</ReportType1> </Extension> </Attachment>
Classes from the DLL do not have a DataContract attribute, but when sent back from my OperationContract , it seems to serialize simply because I get the above results.
How can I say so as not to serialize elements in JSON / XML if they are null, not being able to turn classes from a DLL into a DataContract class? Should I inherit classes from a DLL and somehow override them as a DataContract ? If so, how can I set attributes for existing members of the base classes, then?
Please let me know if further information is required and I will do my best to provide it.