How can I ignore a property when serializing using the DataContractSerializer?

C#.NetWcfSerialization

C# Problem Overview


I am using .NET 3.5SP1 and DataContractSerializer to serialize a class. In SP1, they changed the behavior so that you don't have to include DataContract/DataMember attributes on the class and it will just serialize the entire thing. This is the behavior I am using, but now I need to ignore one property from the serializer. I know that one way to do this is to add the DataContract attribute to the class, and just put the DataMember attribute on all of the members that I want to include. I have reasons, though, that this will not work for me.

So my question is, is there an attribute or something I can use to make the DataContractSerializer ignore a property?

C# Solutions


Solution 1 - C#

Additionally, DataContractSerializer will serialize items marked as [Serializable] and will also serialize unmarked types in .NET 3.5 SP1 and later, to allow support for serializing anonymous types.

So, it depends on how you've decorated your class as to how to keep a member from serializing:

  • If you used [DataContract], then remove the [DataMember] for the property.
  • If you used [Serializable], then add [NonSerialized] in front of the field for the property.
  • If you haven't decorated your class, then you should add [IgnoreDataMember] to the property.

Solution 2 - C#

You might be looking for IgnoreDataMemberAttribute.

Solution 3 - C#

In XML Serializing, you can use the [XmlIgnore] attribute (System.Xml.Serialization.XmlIgnoreAttribute) to ignore a property when serializing a class.

This may be of use to you (Or it just may be of use to anyone who found this question when attempting to find out how to ignore a property when Serializing in XML, as I was).

Solution 4 - C#

Try marking the field with [NonSerialized()] attribute. This will tell the serializer to ignore the field.

https://msdn.microsoft.com/en-us/library/system.nonserializedattribute(v=vs.110).aspx

Solution 5 - C#

What you are saying is in conflict with what it says in the MSDN library at this location:

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx

I don't see any mention of the SP1 feature you mention.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNotDanView Question on Stackoverflow
Solution 1 - C#DougView Answer on Stackoverflow
Solution 2 - C#Paul RuaneView Answer on Stackoverflow
Solution 3 - C#Kris AdamsView Answer on Stackoverflow
Solution 4 - C#Cris ValenzuelaView Answer on Stackoverflow
Solution 5 - C#Tony The LionView Answer on Stackoverflow