Prevent class property from being serialized

Viewed 2297

I added attribute serializable to class but, due to this, class property is getting serialized.

I used [XmlIgnore] to all property but still it is serializing the property

[Serializable]
public class Document
{

    [DataMember]
    [XmlIgnore]
    public string FileURL { get; set; }

    [DataMember]
    [XmlIgnore]
    public string FileSize { get; set; }       

}

It's serialized like below tag-

<a:_x003C_DocumentDetails_x003E_k__BackingField>
  <a:Document>                  
    <a:_x003C_FileType_x003E_k__BackingField>PDF</a:_x003C_FileType_x003E_k__BackingField>
    <a:_x003C_FileURL_x003E_k__BackingField>C:/log/Test.pdf</a:_x003C_FileURL_x003E_k__BackingField>                    
  </a:Document>
</a:_x003C_DocumentDetails_x003E_k__BackingField>
4 Answers

If you are using the [Serializable] attribute, you need to use the [NonSerialized] attribute on any members (public or private) that you don't want serialised.

[DataMember] is used when the class is marked with the [DataContract] attribute and [XmlIgnore] is used when you are explicitly using the XmlSerialiser on a class.

[Serializable]
public class Document {
  [NonSerialized]
  public string FileURL { get; set; }

  [NonSerialized]
  public string FileSize { get; set; }
}

try [JsonIgnore] or [IgnoreDataMember] attribute, that will help you.

If you're using WCF with an "out of the box" configuration, you're probably using the DataContractSerializer to serialize messages, not the XmlSerializer.

In order to have members of your contract class not be serialized, you decorate them with the IgnoredDataMember attribute:

[Serializable]
public class Document
{
    [DataMember]
    public string FileURL { get; set; }

    [IgnoredDataMember]
    public string FileSize { get; set; }
}
Related