序列化
序列化:把对象转化为可传输的字节序列过程称为序列化。通俗说就是将一个对象的状态(各个属性量)保存起来,然后在适当的时候再获得。
反序列化:把字节序列还原为对象的过程称为反序列化。
序列化只是一种拆装组装对象的规则,那么这种规则肯定也可能有多种多样,比如现在常见的序列化方式有:
- JDK(不支持跨语言)
- JSON、XML、Hessian
- Kryo(不支持跨语言)
- Thrift、Protostuff
- FST(不支持跨语言)
序列化目的:以某种存储形式使自定义对象持久化,将对象从一个地方传递到另一个地方,为了对象可以跨平台存储,和进行网络传输(凡是需要进行“跨平台存储”和”网络传输”的数据,都需要进行序列化)
方法
用二进制格式化的序列化方法来序列化Save对象,序列化与反序列化的进行需要依托文件流(FileStream)进行
序列化(保存)
BinaryFormatter.Serialize(FileStream _fileStream, Object _object)
FileStream fs = new FileStream("DataFile.dat", FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
firmatter.Serialize(fs,addresses)
反序列化(读取)
二进制格式化程序的反序列化方法,将文件流转换为一个save对象
Save save = (Save)BinaryFormatter.Deserialize(FileStream _fileStream); //强转
Hashtable addresses = null;
FileStream fs = new FileStream("DataFile.dat", FileMode.Open);
try
{
BinaryFormatter formatter = new BinaryFormatter();
addresses = (Hashtable) formatter.Deserialize(fs);
}
案例
public class App
{
[STAThread]
static void Main()
{
Serialize();
Deserialize();
}
static void Serialize()
{
// Create a hashtable of values that will eventually be serialized.
Hashtable addresses = new Hashtable();
addresses.Add("Jeff", "123 Main Street, Redmond, WA 98052");
addresses.Add("Fred", "987 Pine Road, Phila., PA 19116");
addresses.Add("Mary", "PO Box 112233, Palo Alto, CA 94301");
// To serialize the hashtable and its key/value pairs,
// you must first open a stream for writing.
// In this case, use a file stream.
FileStream fs = new FileStream("DataFile.dat", FileMode.Create);
// Construct a BinaryFormatter and use it to serialize the data to the stream.
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(fs, addresses);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to serialize. Reason: " + e.Message);
throw;
}
finally
{
fs.Close();
}
}
static void Deserialize()
{
// Declare the hashtable reference.
Hashtable addresses = null;
// Open the file containing the data that you want to deserialize.
FileStream fs = new FileStream("DataFile.dat", FileMode.Open);
try
{
BinaryFormatter formatter = new BinaryFormatter();
// Deserialize the hashtable from the file and
// assign the reference to the local variable.
addresses = (Hashtable) formatter.Deserialize(fs);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
throw;
}
finally
{
fs.Close();
}
// To prove that the table deserialized correctly,
// display the key/value pairs.
// foreach (DictionaryEntry de in addresses)
// {
// Console.WriteLine("{0} lives at {1}.", de.Key, de.Value);
// }
addresses.Dump();
}
}