C#序列化
1.为什么需要序列化
诸如在用C#写好的一些对象数据,传递给用Java写的模块来使用的情境中。在不同的语言之间交换一个对象数据存在诸多的不方便之处,因为每一个对象都是立体的,带有很多数据量。因此,我们需要把对象转化为byte或者字符串或者其他更方便传输和识别的数据格式,才可以实现这个情况下的数据交换,所以需要对要传输的一端对数据进进行序列化,在接收数据的一端对数据进行反序列化。
2.什么是序列化
对象序列化(Serilization)就是将对象按照指定的方式,指定的序列组织方式来进行组织。序列化其实就是让数据按照某种规则来排队。序列化——也叫格式化,把数据按照一定的格式来保存;反序列化就是按照序列化的规则还原到原来的格式。
3.怎么实现序列化
常用的序列化方式有三个:
- 把对象转化为byte数组 BinaryFormatter类
// 定义一个学生类,一定要把加上Serilize这个特性才可以被序列化
[Serializable]
public class Student
{
private string _firstName;
private string _lastName;
private int _age;
public string FirstName { get => _firstName; set => _firstName = value; }
public string LastName { get => _lastName; set => _lastName = value; }
public int Age { get => _age; set => _age = value; }
public Student(string fi, string la, int age)
{
this._firstName = fi;
this._lastName = la;
this._age = age;
}
}
// 定义一个BinaryFormatterTest类,实现了序列化和反序列化的功能,两个静态方法
public class BinaryFormatterTest
{
// 传入需要序列化的对象,写成泛型的可以对一切对象通用
public static void ObjectToBinary<T>(T u)
{
string path = "D:\\xx.data";
FileStream fs = new FileStream(path, FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serilize(fs, u);
fs.Close();
}
// 传入已经序列的文件,保存的硬盘地址
public static object BinaryToObject(string path)
{
FileStream fs = new FileStream(path, FileMode.Open);
BinaryFormatter = new BinaryFormatter();
return bf.Deserilize(fs);
}
}
class Program
{
void Serilize()
{
List<Student> stus = new List<Student>
{
new Student("ueh","mdks",18),
new Student("Asd","fdfd",39),
new Student("sshd","fduid",26)
};
BinaryFormatterTest.ObjectToBinary<List<Student>>(stus);
Console.WriteLine("序列化成功);
}
void Deserilize()
{
string str = strig.Empty;
var list = BinaryFormatter.BinatyToObject(@"D:\xx.data") as List<Student>;
foreach (Student item in list)
{
str += $"Name={item.FirstName}.{Item.LastName}" + "\n";
}
Console.WriteLine(str);
}
static void Main()
{
//Serilize();
Deserilize();
Console.ReadKey();
}
}
- 把对象转化为xml文件
3.把对象转为json