Escolar Documentos
Profissional Documentos
Cultura Documentos
70-536 Chapitre 5
Plan
Serialization
Mohamed Romdhani
INSAT, Octobre 2007 2
M. Romdhani, Octobre 2007
What is serialization ?
1
Chapitre 1- Introduction aux technologies J2EE
2
Chapitre 1- Introduction aux technologies J2EE
How to Use XML to Serialize an Object How to Use XML to Deserialize an Object
At a high level, the steps for serializing an object are as follows: To deserialize an object, follow these steps:
1. Create a stream, TextWriter, or XmlWriter object to hold the serialized output. 1. Create a stream, TextReader, or XmlReader object to read the serialized input.
2. Create an XmlSerializer object (in the System.Xml.Serialization namespace) by 2. Create an XmlSerializer object (in the System.Xml.Serialization namespace) by
passing it the type of object you plan to serialize. passing it the type of object you plan to deserialize.
3. Call the XmlSerializer.Serialize method to serialize the object and output the 3. Call the XmlSerializer.Deserialize method to deserialize the object, and cast it to
results to the stream. the correct type.
At the code level, these steps are similar to standard serialization. The The following code sample deserializes an XML file containing a
following console applicatio which requires using System.IO and DateTime object and displays that object’s day of the week and time
System.Xml.Serialization namespace demonstrates the simplicity:
FileStream fs = new FileStream("SerializedDate.XML", FileMode.Open);
// Create file to save the data to
// Create an XmlSerializer object to perform the deserialization
FileStream fs = new FileStream("SerializedDate.XML", FileMode.Create);
XmlSerializer xs = new XmlSerializer(typeof(DateTime));
// Create an XmlSerializer object to perform the serialization
XmlSerializer xs = new XmlSerializer(typeof(DateTime)); // Use the XmlSerializer object to deserialize the data from the file
// Use the XmlSerializer object to serialize the data to the file DateTime previousTime = (DateTime)xs.Deserialize(fs);
xs.Serialize(fs, System.DateTime.Now); fs.Close(); // Close the file
fs.Close(); // Close the file // Display the deserialized time
When run, the application produces a text file similar to the following: Console.WriteLine("Day: " + previousTime.DayOfWeek + ",
<?xml version="1.0" ?> Time: " + previousTime.TimeOfDay.ToString());
<dateTime>2005-12-05T16:28:11.0533408-05:00</dateTime>
3
Chapitre 1- Introduction aux technologies J2EE
To create a class that can be serialized by using XML serialization, you If you serialize a class that meets the requirements for XML
must perform the following tasks: serialization but does not have any XML serialization attributes, the
runtime uses default settings that meet many people’s requirements.
Specify the class as public.
Consider the following simple class:
Specify all members that must be serialized as public. public class ShoppingCartItem {
Create a parameterless constructor. public Int32 productId;
public decimal price;
Unlike classes processed with standard serialization, classes do not private Int32 quantity;
have to have the Serializable attribute to be processed with XML public decimal total;
serialization. public ShoppingCartItem(){}
If there are private or protected members, they will be skipped during }
serialization. Serializing an instance of this class with sample values creates the
following XML :
<?xml version="1.0" ?>
<ShoppingCartItem>
<productId>100</productId>
<price>10.25</price>
<total>20.50</total>
</ShoppingCartItem>
Although attributes will enable you to meet most XML serialization An XML schema defines the structure of an XML document.
requirements, you can take complete control over XML serialization by
implementing the IXmlSerializable interface in your class. If you have an XML schema, you can run the XML Schema Definition
tool (Xsd.exe) to produce a set of classes that are strongly typed to the
For example, you can separate data into bytes instead of buffering schema and annotated with attributes.
large data sets, and also avoid the inflation that occurs when the data When an instance of such a class is serialized, the generated XML
is encoded using Base64 encoding. adheres to the XML schema.
To control the serialization, implement the ReadXml and WriteXml This is a simpler alternative to using other classes in the .NET
methods to control the XmlReader and XmlWriter classes used to read Framework, such as the XmlReader and XmlWriter classes, to parse
and write the XML. and write an XML stream.
4
Chapitre 1- Introduction aux technologies J2EE
When the runtime calls GetObjectData during serialization, you are responsible
for populating the SerializationInfo object provided with the method call.
Simply add the variables to be serialized as name/value pairs using the AddValue
method, which internally creates SerializationEntry structures to store the information.
Any text can be used as the name. You have the freedom to decide which member
variables are added to the SerializationInfo object, provided that sufficient data is
serialized to restore the object during deserialization.
When the runtime calls your serialization constructor, simply retrieve the values of the
M. Romdhani, Octobre 2007 27 variables from SerializationInfo using the names used during serialization.
M. Romdhani, Octobre 2007 28
5
Chapitre 1- Introduction aux technologies J2EE
[Serializable]
Using these events is the best and easiest
way to control the serialization process. class ShoppingCartItem {
public Int32 productId;
The methods do not access the public decimal price;
serialization stream but instead allow public Int32 quantity;
you to alter the object before and after public decimal total;
serialization, or before and after [OnSerializing]
deserialization. void CalculateTotal(StreamingContext sc) {
total = price * quantity;
For a method to respond to one of these }
events, it must meet these requirements: [OnDeserialized]
void CheckTotal(StreamingContext sc) {
Accept a StreamingContext object as a if (total == 0) { CalculateTotal(sc); }
parameter }
Return void }
Have the attribute that matches the Events are supported only for BinaryFormatter serialization
event you want to intercept
For SoapFormatter or custom serialization, you are limited to using the
IDeserializationCallback interface, as discussed in Lesson 1 of this chapter.
To create a custom formatter, implement the IFormatter or You can implement ISerialization to perform custom serialization.
IGenericFormatter interface.
Both BinaryFormatter and SoapFormatter implement the IFormatter BinaryFormatter provides four events that you can use to control parts
interface. The FormatterServices class provides static methods of the serialization process:
(including GetObjectData) to aid with theimplementation of a formatter. OnSerializing, OnSerialized, OnDeserializing, and OnDeserialized.
NOTE .NET 2.0 : Although IFormatter was available beginning with
.NET 1.1, IGenericFormatter is new with .NET 2.0. The StreamingContext class, an instance of which is provided to
methods called during serialization events, gives you information
about the origin or planned destination of the serialization process.
The method performing serialization must specify this information for it
to be useful.
Though few developers will require total control over serialization, you
can implement the IFormatter or IGenericFormatter interfaces to create
custom formatters.
6
Chapitre 1- Introduction aux technologies J2EE
70-536 Chapitre 5
Chapter Summary