CategorySerialize and deserialize data

DataContractSerializer

DataContractSerializer made its first appearance with release of WCF but can operate outside WCF.

DataContractSerializer can serialize types decorated with DataContract, MessageContract, Serializable attributes, types that implement IXmlSerialisable and all public types without Attributes.

During serialization Reference integrity is by default not preserved. You can preserve it by setting “IsReference = true” to DataContract attribute. Note that this approach my cause problems if DataContractSerializer is not serializer who will deserialize data.

 

You can also use OnSerializing, OnSerialized, OnDeserializing, OnDeserialized Attributes to fine-grain your serialization process.

This tutorial will explain how to serialize and deserialize types by decorating type with DataContract attribute.

First we use need to add reference to System.Runtime.Serialization. Secondly we decorate the type with DataContract Attribute, and inside type wee decorate fields and properties with DataMember Attribute. Then we instantiate DataContractSerializer instance and use its WriteObject and ReadObject methods to serialize/deserialize data.

Example of DataContractSerializer:

By using DataMember Attribute we can serialize automatic properties, because property itself will be serialized and not its backing field.

Because DataContractSerializer does not store type and assembly information we need to tell it which is the type we wish to serialize by specifying type in the DataContractSerializer constructor.

As no type or assembly information are preserved be sure to supply KnownType  Attribute to your base class to be able to use inheritance properly.

DataContractSerializer

Data Contract Serializer

 

You can download solution from this link.

To return to other serialization techniques return to this location.

Binary serialization

Today’s topic is Binary serialization, if you wish to read more about serialization or other types of serialization please visit this link:

Binary serialization is type of serialization where type fidelity and reference integrity are preserved, meaning assembly information, private and public fields are being preserved as well as theirs memory locations. You would normally use binary serialization to preserve application state, store it to a backing store (storage medium) and use it later to run application on same computer or maybe multiple other computers.

Hearth of binary serialization is BinaryFormatter class and its Serialize and Deserialize methods. Serialize and Deserialize  methods take two parameters stream and object graph and serialize or deserialize object accordingly. Result of serialization are unreadable to human eye but you can read some information:

Binary Formatter

BinaryFormatter serialization result

As you can see type and field information are preserved.

If you wish serialized data in more readable way you can use SoapFormatter. Note that SoapFormatter is obsolete so use it only for debugging and testing purposes.

SoapFormatter

SoapFormatter serialization result

To mark a type serializable use Serializable attribute to decorate type. Serializable attribute is not inherited so if you wish to serialize both base and derived class decorate both of them with serializable attribute. Other approach would be to implement ISerializable interface.

If you wish not to serialize filed add NonSerialized attribute.

You can serialize null types, but you can not serialize or deserialize null streams.

Properties are not serialized but their private fields are. Do not serialize auto implemented properties because you cannot guarantee that theirs private fields will have the same name on the other machines as they do on yours.

If we wish more control during Serialization/Deserialization processes we can use attributes from System.Runtime.Serialization and apply them to the methods.
Attributes we can use for methods during serialization:
OnSerializingAttribute – use this attribute to prepare data before deserializing . For example encrypt password field or change distance from miles to kilometers.
OnSerializedAttribute – restores type to a status it was before applying OnSerializingAttribute.

Attributes we can use for methods during serialization:
OnDeserializingAttribute – because serialization cannot use constructor, use this attribute for method that will simulate constructor, and maybe set fields to default values.
OnDeserializedAttribute – use this attribute to manually set value of the fields just after serialization process has finished.

 

Example for Binary serialization.

We will try to serialize data from Employee class:

 

 

Download link for entire solution is here.

Serialization and Deserialization

Serialization is the process of transforming an object or object graph
into a stream of bytes or text. Similarly,  deserialization is the process of transforming bytes into an object or object graph.

Object graph: In computer science, in an object-oriented program, groups of objects form a network through their relationships with each other—either through a direct reference to another object or through a chain of intermediate references. These groups of objects are referred to as object graphs.

So, object graph can be a single List of string, entire class or even state of application.

Usage of serialization can wary, weather you want to communicate between two applications on one PC, save state of an Application on your local hard-drive or maybe in cloud… possibilities are endless.

What can I serialize?

You cannot serialize methods or delegates, but you can serialize fields and properties. That is why we can use DTO models (Data transferable models). DTO models are classes with properties that represent data that we want to represent. You have seen some examples so far, like Employee class.

To make this class more readable you could just add DTO suffix after Employee and everybody would know that this is an DTO class.

We will inspect how to serialize and deserialize data by using:

  1. Binary serialization,
  2. Custom serialization,
  3. XML Serializer,
  4. JSON Serializer,
  5. Data Contract Serializer

Among these XML Serializer and JSON Serializer are the most common ones but as we progress between each one of them you will see that other serialization mechanisms have their usage.

 

© 2019 LearnC#WithDarko

Theme by Anders NorenUp ↑