kiran
kiran

Reputation: 45

Prevent class property from being serialized

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>

Upvotes: 3

Views: 3713

Answers (4)

Paul Turner
Paul Turner

Reputation: 39615

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; }
}

Upvotes: 2

Zhaph - Ben Duguid
Zhaph - Ben Duguid

Reputation: 26956

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; }
}

Upvotes: 4

Joker_37
Joker_37

Reputation: 869

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

Upvotes: 3

Mario Lopez
Mario Lopez

Reputation: 1465

Have you tried IgnoreDataMemberAttribute as per the docs?

https://msdn.microsoft.com/en-us/library/system.runtime.serialization.ignoredatamemberattribute.aspx

Upvotes: 0

Related Questions