Serialization
What is Serialization
•
Serialization is the process of converting an
object, or a connected graph of objects, stored
within computer memory, into a linear sequence
of bytes
•
Use the sequence of bytes in several ways:
–
Send it to another process
–
Send it to the clipboard, to be browsed or used by
another application
–
Send it to another machine
–
Send it to a file on disk
Serialization
Object Graph
•
What is an object graph?
–
An object graph is a set of objects with some set
of references to each other
–
The most obvious problem is how to represent the
links between the objects in the Serialized stream
Cat
Cat
Mouse
Duck
Dog
2
1
3
4
9
7
Horse
Serialization
How Serialization Works
•
Because run
-
time metadata 'knows' about each object's
layout in memory, and its field and property definitions, you
can serialize objects automatically, without having to write
code to serialize each field
•
The serialized stream might be encoded using XML, or a
compact binary representation
•
The format is decided by the the Formatter object that you
call:
–
Binary
–
SOAP
–
Custom
Serializaiton
Example
-
VideoLibrary
using
System;
namespace
VideoLibrary
{
[
Serializable
]
public
enum
Genre
{ Drama, Comedy, Western,
ScienceFiction
, Horror, Family };
[
Serializable
]
public
class
VideoInfo
{
public
string
Title {
get
;
set
; }
public
Genre
Category {
get
;
set
; }
public
string
Director {
get
;
set
; }
public
int
Year {
get
;
set
; }
public
TimeSpan
Duration {
get
;
set
; }
public
string
Review {
get
;
set
; }
}
}
Worksheet 4 from
http://www.cse.ohio
-
state.edu/~crawfis/cse459_CSharp/index.html
Serializaiton
Example
-
VideoLibrary
namespace
VideoLibrary
{
public
partial
class
MyVideoLibraryForm
:
Form
{
List
<
VideoInfo
>
videoLib
=
new
List
<
VideoInfo
>();
…
private
void
saveLibraryToolStripMenuItem_Click
(
object
sender,
EventArgs
e)
{
if
(
this
.saveLibraryDialog.ShowDialog
() ==
DialogResult
.OK
)
{
XmlSerializer
s =
new
XmlSerializer
(
videoLib.GetType
());
using
(
TextWriter
w =
new
StreamWriter
(
saveLibraryDialog.FileName
))
{
s.Serialize
(w,
videoLib
);
}
}
}
Worksheet 4 from
http://www.cse.ohio
-
state.edu/~crawfis/cse459_CSharp/index.html
File
-
>Save
menu
Serializaiton
Example
-
VideoLibrary
private
void
openToolStripMenuItem_Click
(
object
sender,
EventArgs
e)
{
if
(
this
.openLibraryDialog.ShowDialog
() ==
DialogResult
.OK
)
{
XmlSerializer
s =
new
XmlSerializer
(
videoLib.GetType
());
using
(
TextReader
reader =
new
StreamReader
(
openLibraryDialog.FileName
))
{
List
<
VideoInfo
>
newVideos
= (
List
<
VideoInfo
>)
s.Deserialize
(reader);
foreach
(
VideoInfo
video
in
newVideos
)
bindingVideoLib.Add
(video);
}
}
}
Worksheet 4 from
http://www.cse.ohio
-
state.edu/~crawfis/cse459_CSharp/index.html
File
-
>Import
menu
Serialization
Scenarios
•
Persistence
•
Remoting
-
By
-
Value
•
Remoting
-
By
-
Reference
•
Transacted Persistence
Serialization
Basic Serialization
•
A Type is NOT Serializable unless Type is
specifically marked as Serializable
•
The Serializable Attribute
•
The Non
-
Serializable Attribute
[Serializable] public class MyClass {}
[Serializable] public class MyClass {
[NotSerialized] int _cashSize;
}
Serialization
•
It is easy to write the individual fields of a
record
object to
a file
•
For example, we can create a record that stores
information about a student
–
Name
–
Address
–
ID number
–
Course enrolled for
–
etc
•
We can output each field of this record to a file (either
text or binary)
Serialization
StudentInfo
Name
Address
ID number
Course Info
Record file
string
string
int
string
Serialization
•
In this example, any program that needs to read the
file needs to know the format of the data
–
2 strings, an
int
and then a string
–
Also whether each item is on a separate line
•
.NET serialization
allows complete objects to be read
or written with a single statement (.NET does the
plumbing for you using reflection).
•
A
serialized object
is an object represented as a
sequence of bytes.
•
Information is stored about the data types of the
objects instance fields as well as their values
–
Allows the object to be reconstructed (de
-
serialized) from the sequence of bytes.
Serialization
StudentInfo
Name
Address
ID number
Course Info
Record file
StudentInfo object
Serialization
•
To serialize an object, the object class needs to be
marked with the
[
Serializable
]
attribute or needs
to implement the
ISerializable
interface
•
Requires the
System.Runtime.Serialization
namespace
•
Also we require a formatter to serialize/de
-
serialize the object before writing to or reading
from file
–
IFormatter
-
BinaryFormatter
–
XMLSerializer
(why is this not an
IFormatter
?)
Serialization
ISerializable
Interface
•
Customize the serialization process
•
If a class implements ISerializable, that
interface will always be called in preference to
default serialization.
•
The ISerializable interface only contains one
method:
void
GetObjectData
(
SerializationInfo
info,
StreamingContext
context);
And
an implied constructor that may be private.
private
<T>
(
SerializationInfo
info,
StreamingContext
)
Serialization
Additional Attributes
•
The serialization framework allows you to also
specify methods to be called when an instance
is being
deserialized
, after it is
deserialized
,
before it is serialized, etc.
–
[
OnDeserialized
]
–
see the
MSDN example
.
Serialization
IDeserializationEventListener
•
If an object implements
IDeserializationEventListener, the serialization
infrastructure will call that class‘
OnDeserialization method as soon as the
entire graph has been deserialized and all fix
-
ups completed
•
Provide a reasonable opportunity for objects
that need to do fix
-
ups based on the state of
their children
Serialization
•
Binary serialization is limited as only .NET
applications can
deserialize
the data stream
•
For more general inter
-
operability
especially across a network,
xml
serialization
is used
–
xml is text based and self
descibing
and
universal
–
Comprised name/attribute pairs
–
xml serialization easy to implement and uses
text streams
Serialization
•
We need to insert xml tags into our
StudentInfo
class
–
Only public properties and fields can be
serialized
[
XmlRoot
("
studentInfo
")]
public class
StudentInfo
{
[
XmlAttribute
("name")] public string Name;
[
XmlAttribute
("address")] public string Address;
[
XmlAttribute
("course")] public string
CourseInfo
;
[
XmlAttribute
("id")] private
int
ID;
public
StudentInfo
()
{ }
public
StudentInfo
(String n, String a, String
ci
,
int
id)
{
Name = n; Address = a;
CourseInfo
=
ci
;
ID = id;
}
}
Enter the password to open this PDF file:
File name:
-
File size:
-
Title:
-
Author:
-
Subject:
-
Keywords:
-
Creation Date:
-
Modification Date:
-
Creator:
-
PDF Producer:
-
PDF Version:
-
Page Count:
-
Preparing document for printing…
0%
Σχόλια 0
Συνδεθείτε για να κοινοποιήσετε σχόλιο