Tải bản đầy đủ - 0 (trang)
2-13. Store a Serializable Object to a File

2-13. Store a Serializable Object to a File

Tải bản đầy đủ - 0trang

CHAPTER 2 ■ DATA MANIPULATION



using

using

using

using

using



System;

System.IO;

System.Collections;

System.Runtime.Serialization.Formatters.Soap;

System.Runtime.Serialization.Formatters.Binary;



namespace Apress.VisualCSharpRecipes.Chapter02

{

class Recipe02_13

{

// Serialize an ArrayList object to a binary file.

private static void BinarySerialize(ArrayList list)

{

using (FileStream str = File.Create("people.bin"))

{

BinaryFormatter bf = new BinaryFormatter();

bf.Serialize(str, list);

}

}

// Deserialize an ArrayList object from a binary file.

private static ArrayList BinaryDeserialize()

{

ArrayList people = null;

using (FileStream str = File.OpenRead("people.bin"))

{

BinaryFormatter bf = new BinaryFormatter();

people = (ArrayList)bf.Deserialize(str);

}

return people;

}

// Serialize an ArrayList object to a SOAP file.

private static void SoapSerialize(ArrayList list)

{

using (FileStream str = File.Create("people.soap"))

{

SoapFormatter sf = new SoapFormatter();

sf.Serialize(str, list);

}

}

// Deserialize an ArrayList object from a SOAP file.

private static ArrayList SoapDeserialize()

{

ArrayList people = null;



88



www.it-ebooks.info



CHAPTER 2 ■ DATA MANIPULATION



using (FileStream str = File.OpenRead("people.soap"))

{

SoapFormatter sf = new SoapFormatter();

people = (ArrayList)sf.Deserialize(str);

}

return people;

}

public static void Main()

{

// Create and configure the ArrayList to serialize.

ArrayList people = new ArrayList();

people.Add("Graeme");

people.Add("Lin");

people.Add("Andy");

// Serialize the list to a file in both binary and SOAP form.

BinarySerialize(people);

SoapSerialize(people);

// Rebuild the lists of people from the binary and SOAP

// serializations and display them to the console.

ArrayList binaryPeople = BinaryDeserialize();

ArrayList soapPeople = SoapDeserialize();

Console.WriteLine("Binary people:");

foreach (string s in binaryPeople)

{

Console.WriteLine("\t" + s);

}

Console.WriteLine("\nSOAP people:");

foreach (string s in soapPeople)

{

Console.WriteLine("\t" + s);

}

// Wait to continue.

Console.WriteLine("\nMain method complete. Press Enter");

Console.ReadLine();

}

}

}

The SOAP file that the example produces is show following. The binary file is not human-readable.



89



www.it-ebooks.info



CHAPTER 2 ■ DATA MANIPULATION




xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAPENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAPENV="http://schemas.xmlsoap.org/soap/envelope/"

xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0" SOAPENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">





<_items href="#ref-2"/>

<_size>3

<_version>3





Graeme

Lin

Andy









2-14. Serialize an Object Using JSON

Problem

You need to serialize an object to or from JavaScript Object Notation (JSON).



90



www.it-ebooks.info



CHAPTER 2 ■ DATA MANIPULATION



Solution

Create a Stream that either writes to the destination you wish to serialize to or is the source of the data

you wish to deserialize from. Create an instance of DataContractJsonSerializer, using the type of the

object that you wish to serialize or deserialize as the constructor argument. Call WriteObject (to

serialize) or ReadObject (to deserialize) using the object you wish to process as a method argument.



How It Works

The DataContractJsonSerializer class is part of the wider .NET data contract support, which allows you

to create a formal contract between a client and a service about the way in which data will be exchanged.

For our purposes, we need only know that Microsoft has included data contract support for most .NET

data types (including collections), allowing easy serialization to and from JSON.



■ Note You will need to reference the System.ServiceModel.Web and System.Runtime.Serialization

assemblies in order to use DataContractJsonSerializer.



When creating an instance of DataContractJsonSerializer, you must supply the type of the object

that you are going to serialize or deserialize as a constructor argument—you can obtain this by calling

the GetType method on any object. To serialize an object, call the WriteObject method using the object

you wish to serialize and the Stream you wish to serialize it to as method arguments. The WriteObject

method will throw an exception if you try to serialize an object that does not match the type you used in

the constructor.

To deserialize an object, call the ReadObject method using a Stream that contains the JSON data you

wish to process—if you have received the JSON data as a string, you can use the MemoryStream class (see

the code following for an illustration of this technique). The ReadObject method returns an object, and

so you must cast to your target type.

To serialize a data type that you have created, use the [Serializable] annotation as follows:

[Serializable]

class MyJSONType

{

public string myFirstProperty { get; set;}

public string mySecondProperty { get; set; }

}

Using [Serializable] will serialize all of the members of your class. If you wish to be selective about

which members are included in the JSON data, then use the [DataContract] annotation at the class

level, and mark each member you wish to be included with the [DataMember] annotation, as follows:



91



www.it-ebooks.info



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

2-13. Store a Serializable Object to a File

Tải bản đầy đủ ngay(0 tr)

×