简体   繁体   中英

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>

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

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

尝试使用[JsonIgnore][IgnoreDataMember]属性,这将对您有所帮助。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM