Tag Archive | Serialization

XML Serialization

As its name suggests, XML serialization is the process of serializing an object into XML format. Quite luckily, the format of the XML file can be massively customized, so be prepared for dumb questions, like which XML file well be the output of this code, or the reverse (even better).

The classes of XML serialization lives in the System.Xml.Serialization namespace. No reference needed, because this namespace is part of the System.Xml.dll, which is linked by Visual Studio for every project.

The main class here is XmlSerializer. Now this class has absolutely nothing to do with the previous formatter classes. It has three useful instance methods, namely Serialize, Deserialize and CanSerialize. Yes, CanSerialize needs an XmlReader and returns true if the read XML file can be serialized by the instance. The Deserialize method is essentially the same as it was at the formatter classes, can read any kind of Stream, or Reader classes (XmlReader included!). However, the Serialize method is very different from the others. It takes a type (only include a single type when you are working with an Object-derived type with no is-a, has-a relationships), and an array of types, for  the respective is-a, has-a relationships. Yes, you need to include every single type that participates in your object’s life.

Read More…

Custom Serialization Formatting

This objective covers the use of the BinaryFormatter and SoapFormatter classes. I frankly don’t understand why they should be separated from the rest, with a title of custom serialization, but I guess we should just learn it.

These classes lives in the System.Runtime.Serialization.Formatters namespace. Even better, BinaryFormatter lives in the Binary namespace, and SoapFormatter in the Soap namespace. You will need to set a reference on the System.Runtime.Serialization.Formatters.Soap namespace in order to use the SoapFormatter class. BinaryFormatter is included by default.

BinaryFormatter serializes or deserializes yoir objects into a binary object graph. It will need two things to do so: a stream (not necessary a file stream) and an object, marked as Serializable. By default, all public fields and properties are serialized (and private fields with public properties). You can override this setting by mark your fields with the NonSerializable or OptionalField attribute. The latter is useful when dealing with version-compatible serialization.

Read More…

Serialization and Deserialization

Serialization is the process of persisting the current state of an object into a stream in such a way that it contains all information to be deserialized into the same object when needed. You’d do this typically when you’re dealing with remoting services, or when working with web services.

There are two types of serialization in the .NET Framework:

  • Serialization by creating object graphs
  • XML serialization

Read More…