• TwitterFacebookGoogle PlusLinkedInRSS FeedEmail

Datacontract Attribute Serializable

18.08.2019 
Datacontract Attribute Serializable 5,0/5 7139 votes

Data Contract Basics. This attribute can be applied to classes, structures, and enumerations. The DataMemberAttribute attribute must then be applied to each member of the data contract type to indicate that it is a data member, that is, it should be serialized. For more information, see Serializable Types.

The Xmlr has been in .Net since version 1.0 and has served us well for everything from Remoting, Web Services, serializg a file, etc. ever .Net 3.0 the DataContractr came along. And all of a sudden a lot of guidance suggests that we should use it over the old tried and true Xmlr. even uses this as the default mechanism for serialization. The question is, “Is it really better?”. The verdict is yes, and no. Like most thgs it depends on your implementation and what you need. For , you should prefer use the DataContractr. If you need full control over the xml looks though, you should go back the Xmlr.
Lets look at the both of these detail and leave it up to you decide which is best for your implementation. Here are a few of the advantages and disadvantages of each of them:
XmlrDataContractr
Advantages:1. Opt-out rather than opt- properties to serialize. This mean you don’t have to specify each and every property to , only those you don’t wan 2. Full control over a property is d includg it it should be a node or an attribute
Disadvantages:1. Can only properties
3. Properties must have a get and a set which can result some awkward design
5. Cannot understand the DataContractAttribute and will not it unless there is a SerializableAttribute o
Advantages:1. Opt- rather than opt-out properties serialize. This mean you specify what you want
2. Because it is opt you can serialize not only properties, but also fields. You can even non-public members such as private or protected members. And you dont need a set on a property either (ever without a setter you can serialize, but not de)
3. Is about 10% faster than Xmlr the data because sce you don’t have full control over it is , there is a lot that can be done optimize the serialization/deserialization process.
4. Can understand the SerializableAttribute and know that it needs be d
Disadvantages:1. No control over the object is d outside of settg the name and the order

What is Serialization?

Let’s start with the basics. Serialization has been a key part of .Net since version 1. It is basically the process of converting an object instance into a portable and transferable format. The objects can be serialized into all sorts of formats. Serializing to Xml is most often used for its interoperability. Serializing to binary is useful when you want to send the object from one .Net application to another. .Net even supports the terfaces and base es to build your own serializes. There are libraries out there to comma delimited strgs, JSON, etc.
Deserialization is basically the reverse of serialization. Its the process of taking some data (Xml, binary, etc) and converting it back an object.

What is the XmlSerialzer?

For those that may not be familiar with System.Xml.Serialization.Xmlr let’s go over it briefly. This is the xml serializer that has been around since .Net version one. To serialize or deserialize an object, you basically just need to create an stance of the XmlSerializer for the type you want to work with, then just call Serialize() or Deserialize(). It works with streams, so you could any stream such as an MemoryStream, FileStream, etc.
ever not just any object can be d. It supports a number of the base types .Net and most cusm types. Many people thk that theSerializableAttribute is required on the class order for it to be serializable by the XmlSerializer, but this is not the case. It is good practice to use the SerializableAttribute, but it not required. As long as your contas all types that the r understands, then it will work. You need break outIXmlSerializable to implement your own custom serialization for types that the XmlSerializer cannot understand. Any public property that is of a known serializable type and has a get and set will be d by the XmlSerialzer. This can be referred to as an “opt-out” approach, because you chose what you don’t want to clude, not what you want clude.
There are a number of attributes you can use your change it is d:
Setattribute non serializable attribute
  1. System.Xml.Serialization.XmlIgnoreAttribute: This is used to mark a public property as “not be serialized”. This is the “opt-out” approach used by the Xmlr. There are no properties on this attribute.
  2. System.Xml.Serialization.XmlRootAttribute: This is used on the itself change the name or namespace of the root node. The followg properties are supported on the attribute:
    1. AttributeName: Gets or sets the name of the XML attribute.
    2. DataType: Gets or sets the XSD data type of the XML attribute generated by the Xmlr.
    3. Form: Gets or sets a value that dicates whether the XML attribute name generated by the Xmlr is qualified.
    4. Namespace: Gets or sets the XML namespace of the XML attribute.
    5. Type: Gets or sets the complex type of the XML attribute.
    6. TypeId: When implemented a derived , gets a unique identifier for this Attribute.
  3. System.Xml.Serialization.XmlAttributeAttribute: the property as an xml attribute. You can specify thgs such as the name use (instead of the property name). The followg properties are supported on the attribute:
    1. AttributeName: Gets or sets the name of the XML attribute.
    2. DataType: Gets or sets the XSD data type of the XML attribute generated by the Xmlr.
    3. Form: Gets or sets a value that dicates whether the XML attribute name generated by the Xmlr is qualified.
    4. Namespace: Gets or sets the XML namespace of the XML attribute.
    5. Type: Gets or sets the complex type of the XML attribute.
    6. TypeId: When implemented a derived , gets a unique identifier for this Attribute.
  4. System.Xml.Serialization.XmlElementAttribute: Serialize the property as an xml element. You can specify things such as the name to use (stead of the property name), whether or not to serialize it if it is null, the order to the property relative other properites, etc. The followg properties are supported on the attribute:
    1. ElementName: Gets or sets the name of the XML element.
    2. DataType: Gets or sets the XSD data type of the XML attribute generated by the Xmlr.
    3. Form: Gets or sets a value that dicates whether the XML attribute name generated by the Xmlr is qualified.
    4. Namespace: Gets or sets the XML namespace of the XML attribute.
    5. IsNullable: Gets or sets a value that dicates whether the Xmlr must a member that is set to nullNothingnullptra null reference (Nothing Visual Basic) as an empty tag with the xsi:nil attribute set true.
    6. Order: Gets or sets the explicit order which the elements are serialized or ded.
    7. Type: Gets or sets the complex type of the XML attribute.
    8. TypeId: When implemented a derived , gets a unique identifier for this Attribute.
Here is an example setup to use the Xmlr. The only thg fancy here is that I don’t want the Social Security number:

What is the DataContractr?

The System.Runtime.Serialization.DataContractr is new in .Net 3.0 and was designed for contract-first development and speed. Specifically it was brought in to be used by , but can be used for general serialization as well. Using the DataContractSerializer isn’t that much different than using the XmlSerializer. There are a few more options, but the only real key difference is that you use a WriteObject() method to serialize instead of a Serialize() method and a ReadObject() method to deserialize stead of a De() method. It works with the same types of streams, so you can write memory, files, etc.
One thing to note: before you can use the DataContactSeriliazer, you must include a reference to System.Runtime.Serialization. mscorelib gives you some parts of System.Runtime.Serialization, but you must clude this reference get the DataContactSeriliazer and the associated attributes.
Aga, not just any object can be d. It supports a number of the base types .Net and most cusm types. One nice advantage that the DataContractSerializer has over the XmlSerializer is that it understands the SerializableAttribute and classes built for the XmlSerializer or ISerializable. So if your is declared with an DataContactAttribute and it contas a type that uses the SerializableAttibute, all will be well. Unlike the Xmlr though you must defe either the SerializableAttribute or the DataContractAttributeon the order for it be serializable by the DataContractr.
The DataContactSerializer implements an “opt-in” approach. The basically means that you have to explicitly say what will be serialized by adding the DataMemeberAttribute to it. The nice thg about this is that this attribute can be applied to fields and well as properties, you can set it on any access modified (private, protected, etc) not just public, and you can use it on properties that do not have a “set”. However if you label a property that doesn’t have a “set”, then you can only serialize that property. You won’t be able to de it sce it has no idea how to set the property. This also means you cant use it for communication over . But you can still use a “private set” ensure that your model is clean. However, you cannot specify that properties should be xml attributes and control other more complex thgs about the xml will look. It hurts not havg this flexibility, but because of this rigidness, the format is highly predictable and the serializer can make some big optimizations. The DataContractSerializer can serialize and deserialize about 10% faster than the Xmlr. This can be pretty significant if you are workg with a lot of data.
  1. System.Runtime.Serialization.DataContactAttribute: Declares that the is serializable and allows you to specify the namespace and name to it as. This is similar a combination of the SerializableAttribute and XmlRootAttribute the Xmlr. The followg properties are supported on the attribute:
    1. Name: Gets or sets the name of the data contract for the type.
    2. Namespace: Gets or sets the namespace for the data contract for the type.
    3. TypeId:When implemented a derived , gets a unique identifier for this Attribute.
  2. System.Runtime.Serialization.DataMemberAttribute: This is used to declare a property or a field be d. This can work with any access modifier. The followg properties are supported on the attribute:
    1. EmitDefauleValue: Gets or sets a value that specifies whether serialize the default value for a field or property beg d.
    2. IsRequired: Gets or sets a value that instructs the serialization engine that the member must be present when reading or deserializg.
    3. Name: Gets or sets a data member name.
    4. Order: Gets or sets the order of serialization and deserialization of a member. This can be pretty powerful if you have fields that might depend on one another and you really need defe the order that the properties are serialize and ded .
    5. TypeId: When implemented a derived , gets a unique identifier for this Attribute.
If you are gog work with the DataMemberAttribute, here is an concise post about best practices around it:http://blogs.msdn.com/drnick/archive/2008/02/22/datamember-best-practices
Below example setup to use the DatContractr. Notice that I am explicitly settg the DataMemberAttribute on the properties I want , but not on the others.
One other important thg talk about with the DataContractr are the ServiceKnownTypeAttribute and KnownTypeAttribute attributes. These are similar the XmlcludeAttribute used by the Xmlr. When used in , these identify what types should be represented the WSDL that is generated.
The KnownTypeAttribute specifies types that should be recognized by the DataContractr when serializing and deserializing a type. It is applied to a class and basically specifies what other types are used the class. You don’t need to specify known .Net types, but any custom es should be added here. This attribute can be used multiple times identify multiple types.
The ServiceKnownTypeAttribute specifies known types to be used by a service when serializing or deserializing. It is applied to a ServiceContract or to an OperationContract and specifies what types are used in the methods. Aga (like the KnownTypeAttribute), you don’t need to specify known .Net types and this attribute can be used multiple times identify multiple types.

What about the NetDataContractr?

I haven’t really mentioned this yet because it is just like the DataContractr, but there is also a System.Runtime.Serialization.NetDataContractr. It differs from the DatContactSerializer in that it includes CLR type information in the serialized xml, whereas the DataContractSerializer does not. So it can only work if the serializing and derserializing ends share the same CLR types. The nice thg about this r is that since the CLR type formation is sent around, you don’t have implement the ServiceKnownTypeAttirbute or KnownTypeAttribute. Like the DataContractSerializer it can work types that implement either the DataContractAttribute, SerializableAttribute, or ISerializable.
Datacontract attribute serializable meaning
I don’t recommend usg this r often. If possible you should declare your known types explicitly for better understand of the code and of course for the greaterteroperability.

Why another xml r?

Datacontract
So why the need to even create another xml serializer? The XmlSerializer has served us well over the years. Well part of it it speed. Sce the DataContracts are faster to because the structure is predictable and can be more highly optimized. This results in about a 10% performance gain. If you are working with pure the gain in speed is probably worth the trade off loss of control over what the Xml is to look like. Sometimes you might need to control what the xml looks like to get it to fit to some other schema. If that is the case, then you will want to switch the Xmlr.
There is more to the story. Microsoft wants us think of in terms of “Contracts” with Wcf. We often hear the term “Contract First Development”. Some of this principal is already in play by forcing all Services to be defined in an interface (contract). the old days of pure WebServices, you could just tag a as WebService and you didn’t need a separate interface or contract. some respects, the DataContractr is pushg us down this route o. By declaring a class as a DataContract and explictily setting the DataMembers, you are buildg a contract of how the should look. One could argue that you could do this through the Serializable attribute, ever you don’t define what goes in the contract. stead you only specify what isn’t suppose to be serialized and the serializer decides what is should . There is no way to look at the class or use reflection and really get a good feel for the data contract for the . While with the DataContract and DataMember attributes, you could use reflection see exactly what the contract is.

to change use a different r?

By default uses the DataContactSerializer, so if you want to use it, you need to do nothg else. If you want to use the Xmlr through, all you need do is add the System.ServiceModel.XmlrFormatAttribute to the contact interface. The nice thing about this attribute is that it can be applied to the entire service contract, or just to an operation contract. So you could keep the entire service as a whole usg the DataContractr, but only the methods you chose use the Xmlr.
You can also set the service use the XmlSerilizer by default, but specify which methods use the DataContractr with the help of theSystem.ServiceModel.DataContractFormatAttribute:
Now what about changg to use the NetDataContractSerializer. Or what if I want to use a different r or create my own? order to do this you need to create a cusm operation behavior using the IOperationBehavior terface and the Attribute .
Here is an example of a custom operation behavior written to use the NetDataContractSerialier. You could use this, build your own, or modify it work with a differentr.
Once you have this you can just mark up your service like before usg the new attribute:

When use which r?

For , you should prefer use the DataContractr. If you need full control over the xml looks though, you should go back to the XmlSerializer. If you are doing general serialization, it is up to you, but I would weigh out the advantages and disadvantages. I would still prefer the DataContractSerializer for the same reasons I prefer it for . I do not recommend usg the NetDataContractr unless you have to. You can lose o much teroperability and its not as descriptive.
If you need some custom xml serializer, by all means go ahead and implement it. supports any r you can throw at it. Just be careful not “revent the wheel”. The Xmlr is very configurable and may suit your needs. If that doesn’t work, then ISerializable gives you full control.
Active2 years, 11 months ago

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?

NotDanNotDan
16.5k34 gold badges106 silver badges152 bronze badges

5 Answers

Datacontract Attribute Serializable List

Paul RuanePaul Ruane
29.5k10 gold badges57 silver badges74 bronze badges

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:

Datacontract Attribute Serializable Example

  • 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.
DougDoug
4,2943 gold badges25 silver badges32 bronze badges

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).

Kris AdamsKris Adams

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

Protector one
4,0243 gold badges41 silver badges67 bronze badges
Cris ValenzuelaCris Valenzuela

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

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

Tony The LionTony The Lion
41.4k52 gold badges201 silver badges364 bronze badges

Not the answer you're looking for? Browse other questions tagged c#.netwcfserialization or ask your own question.