一、什么是序列化和反序列化?
序列化:把对象转换为可传输的字节序列的过程 称为序列化
反序列化:把字节序列还原为对象的过程 称为反序列化
简单理解:
序列化就是把想要存储的数据转换为字节序列用于存储或传递
反序列化就是把存储或收到的字节序列信息解析读取出来使用
序列化跟自己手动一个一个存是一样的,只是自动化了而已
二、Xml的序列化
第一步:准备一个要被序列化的数据结构类
第二步:进行序列化
关键字
XmlSerializer 用于序列化对象为Xml的关键类
StreamWriter 用于存储文件流
using 用于方便流对象释放和销毁
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using UnityEngine;
//第一步:准备一个要被序列化的数据结构类
public class Lesson1Test
{
//各种访问修饰符的各种类型的变量
public int testPublic = 10;
private int testPrinate = 11;
protected int testProtected = 12;
internal int testInternal = 13;
public string testPublicStr = "123";
public int testPro { get; set; }
public LessonTest2 testClass = new LessonTest2();
}
public class LessonTest2
{
public int test1 = 1;
public float test2 = 1.1f;
public bool test3 = true;
}
public class Lesson1 : MonoBehaviour
{
void Start()
{
//第二步:进行序列化
// 要把这个对象存储为一个Xml文件
Lesson1Test lt = new Lesson1Test();
// 确定存储路径
string path = Application.persistentDataPath + "/Lesson1Test.xml";
// using配合StreamWriter来写入数据
using (StreamWriter stream = new StreamWriter(path))
{
// 开始对Xml为文件序列化
XmlSerializer s = new XmlSerializer(typeof(Lesson1Test));
// 参数1 文件流对象 (写到哪里?)
// 参数2 要被序列化的对象 (写谁?)
// 这句代码的意思就是,对Lesson1Test这个类进行翻译,将其翻译成Xml文件,并写入到对应的文件流中
s.Serialize(stream, lt);
}
}
}
执行:
找到persistentDataPath路径 找到被保存下来的Xml文件:
与第一步中准备的数据对比可得出结论:
1.根节点的名字就是传入的type类的名字
2.它只会存储public的变量
3.类对象中的成员属性也被存储了
补充:
后续又继续往被存储的数据中添加了数组、List、Dictionary:
public int[] arrayInt = new int[] { 5, 6, 7 };
public List<int> listInt = new List<int> { 9, 8, 7, 6 };
public List<LessonTest2> listItem = new List<LessonTest2>() { new LessonTest2(), new LessonTest2() };
public Dictionary<int, string> testDic = new Dictionary<int, string>() { { 1, "哈" }, { 2, "哈哈" } };
运行后得出结论:
1.数组、List也能被存储
2.补充结论:引用类型的变量,如果为null,则不会被序列化
3.唯独不支持Dictionary,会直接报错
如果想支持字典序列化 看这里☞点我
三.自定义节点名 或 设置属性
从上文可得知
存储下来的xml文件都是以节点存储的,并没有属性
可通过在变量前加特性
只改名: [XmlElement(“新名字”)]
改名同时变为属性:[XmlAttribute(“新名字”)]
告诉它在存的时候 哪些想让它变成属性,并传入新的名字
把上文中的LessonTest2类改为:
public class LessonTest2
{
[XmlAttribute("Lv")]
public int test1 = 1;
[XmlAttribute("Atk")]
public float test2 = 1.1f;
[XmlAttribute("Sex")]
public bool test3 = true;
}
运行:
补充:
如果想改List中成员的名字呢?
该自己名字: [XmlArray(“Item”)]
该成员名字: [XmlArrayItem(“新名字”)]
[XmlArray("Item")]
[XmlArrayItem("Num")]
public List<int> listInt = new List<int> { 9, 8, 7, 6 };
运行: