2

I’m using DataContractSerializer for serialization/deserialization. I need to ignore a particular property of an instance gets serialized which used as a property in another class. Here I have provided the simple code structure for your references. I have tried IgnoreDataMember and XmlIgnore attributes, but these not worked.

[DataContract(Name ="Sample")]
public class Sample1
{
    [DataMember]
    public Sample2 s2 { get; set; }
}

[KnownType("KnownTypes")]
public class Sample2
{
    [DataMember]
    public Sample3 s3 { get; set; }
}
public class Sample3
{
    public string property1 { get; set; }

    public string property2 { get; set; }

    //No need to serialize this property while serializing "S3" property in "Sample2" class.
    //Is it possible???
    public string property3 { get; set; }
}
dbc
  • 104,963
  • 20
  • 228
  • 340
MOHANRAJ G
  • 75
  • 9
  • `DataContractSerializer` doesn't support conditional serialization of properties out of the box. See e.g. [ShouldSerialize pattern and DataContractSerializer](https://stackoverflow.com/q/11394587) and [How can I prevent a datamember from being serialized](https://stackoverflow.com/q/8010677) and [Custom DataContractSerializer](https://stackoverflow.com/q/42460674) for details and workarounds. – dbc Jan 25 '18 at 09:23
  • @HimBromBeere - The linked [duplicate](https://stackoverflow.com/questions/1791946/how-can-i-ignore-a-property-when-serializing-using-the-datacontractserializer) asks how to *unconditionally* ignore a property. This question is asking how to *conditionally* ignore a property, specifically when serializing a data object inside another data object. – dbc Jan 25 '18 at 09:29
  • Should the property *never* be serialized, or only when wrapped within an instance of `Sample2`?. In other words: should `Sample3.property3` be serialized, if `Sample1` would have a property of `Sample3`? – MakePeaceGreatAgain Jan 25 '18 at 09:33
  • @HimBromBeere - That was my interpretation of *No need to serialize this property while serializing "S3" property in "Sample2" class.* Can the OP please confirm? – dbc Jan 25 '18 at 09:34
  • @dbc I assumed so also (after your comment), however OP didn´t mention that case explicitely, which is why I didn´t reopen the question until now. – MakePeaceGreatAgain Jan 25 '18 at 09:37
  • Hi @HimBromBeere, he asks "Property 3" never be serialized when serializing "S3" data object used by "Sample2". – Prithiv Jan 25 '18 at 09:59

0 Answers0