Why serialization and serialization operations [included]

Source: Internet
Author: User
Tags xml attribute

Indexed 1:

My understanding:
For example, a class is used to describe a contract, and after the class is instantiated, the field in the class stores the contract information, if you want to send the instance of this class to another machine, another form, or want to save this class for later use (persistence object ), this class can be serialized (serialization is actually a message stream), transmitted or saved, and then deserialized to regenerate this object.

 

Why do you want to use serialization? There are two most important reasons for serialization: one is to keep the object state in the storage media so that accurate copies can be re-created in the future; another reason is to use a value to extract an object from an application.ProgramThe domain is sent to another application domain. For example, serialization can be used to save the session state in ASP. NET and copy the object to the clipboard of Windows Forms. Remote processing can also use serialization to pass objects from one application domain to another through values.

Serializing the object status
That is, the value of the object data member is irrelevant to the method.

 

Serialization is required for cross-application domain communication.
And when using Web Services

 

I. binaryformatter serialization

Serialization is easy to understand, that is, writing memory to the hard disk, or writing it To the memory (this content will be shown in the following example ). deserialization reads information from the hard disk to the memory. that's easy. Now let's look at the following example!

In this articleArticleI will use the binaryformatter serialization class book as an example. I hope you can deeply understand what serialization is.

Definition class book:

[Serializable]
Public class Book
{
String name;
Float price;
String author;

Public book (string bookname, float bookprice, string bookauthor)
{
Name = bookname;
Price = bookprice;
Author = bookauthor;
}
}

Added the attribute serializable. (If this attribute is not added, a serializationexception will be thrown ).

Mark the book as serializable. of course, there is another way to make the class Book serializable, that is, implementing the iserializable interface. note that the serializable attribute cannot be inherited !!!

If you don't want to serialize a variable, what should you do? It's easy to add the attribute [nonserialized] before it. For example, I don't want to serialize it.

String author;

Then I only need

[Nonserialized]

String author;

Now, let's show you how to implement serialization:

We use namespace:

Using system;

Using system. IO;

Using system. runtime. serialization. formatters. Binary;

 

First create a book instance, like this:

Book = New Book ("Day and night", numbertype = "1" TCSC = "0"> 30366f, "Bruce ");

Then, of course, we need to create a file, which is used to store the information we want to serialize.

Filestream FS = new filestream (@ "C: \ book. dat", filemode. Create );

Serialization implementation is also very simple, like this:

Binaryformatter formatter = new binaryformatter ();
Formatter. serialize (FS, book );

Easy! Now I will list the entire originalCode, Including deserialization.

Static void main (string [] ARGs)
{
Book = New Book ("Day and night", 30366f, "Bruce ");

Using (filestream FS = new filestream (@ "C: \ book. dat", filemode. Create ))
{
Binaryformatter formatter = new binaryformatter ();
Formatter. serialize (FS, book );
}

Book = NULL;

Using (filestream FS = new filestream (@ "C: \ book. dat", filemode. Open ))
{
Binaryformatter formatter = new binaryformatter ();
Book = (book) formatter. deserialize (FS); // you should note that the returned value is object.
}
}

If something is wrong, please correct it more .....

Do not forget: using system. runtime. serialization. formatters. Binary;
Namespace.

 

Indexed 2:

It was good to use binaryformatter for serialization. However, it was found that there was no way to perform the binaryformatter operation in wince recently. It was uncomfortable to change it to binarywriter and binaryreader for reading and writing, I suddenly thought I could use XML for serialization? So I checked some information on the Internet and wrote some practical code and made some records to avoid forgetting it later.

Serialized object

Public class people
{
[Xmlattribute ("name")]
Public string name
{Set; get ;}
[Xmlattribute ("Age")]
Public int age
{Set; get ;}
}
[Xmlroot ("root")]
Public class student: People
{
[Xmlelement ("class")]
Public string class
{Set; get ;}
[Xmlelement ("Number")]
Public int number
{Set; get ;}
}

Void main (string [] ARGs)

{

Student Stu = new student ()
{
Age = 10,
Class = "Class One ",
Name = "Tom ",
Number = 1
};
Xmlserializer SER = new xmlserializer (typeof (student ));
Ser. serialize (file. Create ("C: \ x. xml"), Stu );

}

Deserialization object

Xmlserializer SER = new xmlserializer (typeof (student ));
Student Stu = Ser. deserialize (file. openread ("C: \ x. xml") as student;

Object array serialization

Public class people
{
[Xmlattribute ("name")]
Public string name
{Set; get ;}
[Xmlattribute ("Age")]
Public int age
{Set; get ;}
}
[Xmlroot ("root")]
Public class student: People
{
[Xmlelement ("class")]
Public string class
{Set; get ;}
[Xmlelement ("Number")]
Public int number
{Set; get ;}
}

Void main (string [] ARGs)

{

List <student> stulist = new list <student> ();
Stulist. Add (new student () {age = 10, number = 1, name = "Tom", class = "Class One "});
Stulist. Add (new student () {age = 11, Number = 2, name = "Jay", class = "Class Two "});
Stulist. Add (new student () {age = 12, number = 3, name = "Pet", class = "Class One "});
Stulist. Add (new student () {age = 13, number = 4, name = "may", class = "Class Three "});
Stulist. Add (new student () {age = 14, Number = 5, name = "Soy", class = "Class Two "});
Xmlserializer SER = new xmlserializer (typeof (list <student> ));
Ser. serialize (file. Create ("C: \ x. xml"), stulist );

}

Reverse Sequence of object Array

Xmlserializer SER = new xmlserializer (typeof (list <student> ));
List <student> stulist = Ser. deserialize (file. openread ("C: \ x. xml") as list <student>;
Foreach (student s in stulist)
{
MessageBox. Show (string. Format ("{0 }:{ 1 }:{ 2 }:{ 3 }",
S. Name, S. Age, S. Class, S. Number ));
}

Serialize dirctionary

Public struct directionlist
{
[Xmlattribute ("name")]
Public string name;
[Xmlelement ("value")]
Public int value;
}

Void main (string [] ARGs)

{

dictionary List = new dictionary ();
list. add ("1", 100);
list. add ("2", 200);
list. add ("3", 300);
list. add ("4", 400);
list. add ("5", 500);
list. add ("6", 600);
list. add ("7", 700);
list. add ("8", 800);
list. add ("9", 900);

List <directionlist> dirlist = new list <directionlist> ();
Foreach (VAR s in List)
{
Dirlist. Add (New directionlist () {name = S. Key, value = S. Value });
}
Xmlserializer SER = new xmlserializer (typeof (list <directionlist> ));
Ser. serialize (file. Create ("C: \ x. xml"), dirlist );

}

It is worth noting that in xmlserializer, dirctionary <> type objects are not supported, so when serializing the most common type, only a type that can be serialized can be created according to its format. Here I define a struct, and you can also define other classes. Put the data in the dictionary <> into the struct in sequence and then you can put the data in the stream.

[Xmlattribute ("name")] indicates that this field is used as an XML attribute, and the attribute name follows ""

[Xmlelement ("value")] means to use this field as an XML element.

 

Deserialization dirctionary

Xmlserializer SER = new xmlserializer (typeof (list <directionlist> ));
List <directionlist> dirlist = Ser. deserialize (
File. openread ("C: \ x. xml") as list <directionlist>;
Foreach (var v in dirlist)
{
Console. writeline ("{0 }:{ 1}", V. Name, V. value );
}

In fact, I don't like this name, and it seems a bit Resident Evil feel, but that's it. There's no such thing as a fancy, deserialize deserialization. I really hope. Net can be integrated with dirctionary <> objects, so it's easy for us to be lazy.

Arrays are common types in the teams to be serialized, followed by images.

Serialize Images

Public struct imagestruct
{
[Xmlattribute ("Number")]
Public int number;
[Xmlelement ("image")]
Public byte [] picture;
}

Void main (string [] ARGs)

{

Imagestruct S = new imagestruct () {number = 1, picture = file. readallbytes (@ "11.jpg ")};
Xmlserializer SER = new xmlserializer (typeof (imagestruct ));
Filestream FS = file. Create ("C: \ x. xml ");
Ser. serialize (FS, S );
FS. Close ();

}

In the same way, the structure is used to save the image. Here I add an image name and it will be easier to find it.

Image deserialization

Xmlserializer SER = new xmlserializer (typeof (imagestruct ));
Imagestruct S = (imagestruct) SER. deserialize (file. openread ("C: \ x. xml "));
Picturebox1.image = image. fromstream (New memorystream (S. Picture ));

There is no way to use memorystream for caching, which will be faster. In fact, I don't feel much about it.

Image array serialization

Public struct imagestruct
{
[Xmlattribute ("Number")]
Public int number;
[Xmlelement ("image")]
Public byte [] picture;
}

Void main (string [] ARGs)

{

List <imagestruct> imagelist = new list <imagestruct> ();
Imagelist. Add (New imagestruct ()
{
Number = 1,
Picture = file. readallbytes (@ "11.jpg ")
});
Imagelist. Add (New imagestruct ()
{
Number = 2,
Picture = file. readallbytes (@ "22.jpg ")
});

Xmlserializer SER = new xmlserializer (typeof (list <imagestruct> ));
Filestream FS = file. Create ("C: \ x. xml ");
Ser. serialize (FS, imagelist );
FS. Close ();

}

Deserialization of image Arrays

xmlserializer SER = new xmlserializer (typeof (list );
List S = (list ) Ser. deserialize (file. openread ("C: \ x. XML ");
var im = from I in S
where I. number = 1
select I. picture;

// Var im = S. Where (P => P. Number = 1). Select (P => P. Picture );
Foreach (VAR image in IM)
{
Picturebox1.image = image. fromstream (
New memorystream (image ));
}

The array structure is also queried by using LINQ, which makes it easy to query images.

 

Included 3:

Serialization facilitates object transmission and storage;
It can convert objects into XML/bit streams;
It is the basis of Session (out-of-process/sqlserver mode), viewstate, WebService, and remoting.

 

Indexed 4:

For example, student
Public class student
{
Public int ID;
Public string name;
Public bool sex;
Public datetime birthday;
...
}

// Serialize to byte []
Memorystream FS = new memorystream ();
Byte [] TMP = NULL;
Binaryformatter formatter = new binaryformatter ();
Formatter. serialize (FS, student );
TMP = FS. toarray ();
Store TMP as bianry data to the database

// Deserialization directly generates the student class
Memorystream FS = new memorystream ();
Student = NULL;
FS = new memorystream (TMP );
FS. Position = 0;
Binaryformatter formatter = new binaryformatter ();
Student = formatter. deserialize (FS );
For ease of operation, you do not need to assign values one by one.

However, there are also some problems. For example, after the database is saved, the class student adds the attribute, so the deserialization fails!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.