Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 214
NotDan Avatar asked Nov 24 '09 18:11

NotDan


People also ask

How do you ignore property serializable?

To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.

Why is serialization not good?

It is not future-proof for small changes If you mark your classes as [Serializable] , then all the private data not marked as [NonSerialized] will get dumped. You have no control over the format of this data. If you change the name of a private variable, then your code will break.

How does serialize work?

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.

When should serialization be used?

Here are some examples of using serialization: - Storing data in an object-oriented way to files on disk, e.g. storing a list of Student objects. - Saving program's states on disk, e.g. saving state of a game. - Sending data over the network in form objects, e.g. sending messages as objects in chat application.


2 Answers

You might be looking for IgnoreDataMemberAttribute.

like image 132
Paul Ruane Avatar answered Sep 29 '22 18:09

Paul Ruane


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.
like image 23
Doug Avatar answered Sep 29 '22 18:09

Doug