一种需要打序列化标签
public static bool Xmlserialize(string path, System.Object obj)
{
try
{
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
{
using (StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8))
{
//XmlSerializerNamespaces namespaces= new XmlSerializerNamespaces(); //可以将xml的命名空间去掉,如果有需求
//namespaces.Add(string.Empty, string.Empty);
XmlSerializer xs = new XmlSerializer(obj.GetType());
xs.Serialize(sw, obj);
}
}
}
catch (Exception e)
{
Debug.LogError("此类无法转换成xml" + obj.GetType() + "," + e);
}
return false;
}
反序列化1
/// <summary>
/// Xml 的反序列化
/// </summary>
/// <param name="path"></param>
/// <param name="type"></param>
/// <returns></returns>
public static System.Object XmlDeserialize(string path, Type type)
{
System.Object obj = null;
try
{
Debug.Log(path + " 反序列化成xml的路径");
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
XmlSerializer xs = new XmlSerializer(type);
obj = xs.Deserialize(fs); //反序列化出来成为对象
}
}
catch (Exception e)
{
Debug.LogError("此类无法转换成xml" + obj.GetType() + "," + e + path);
}
return obj;
}
一种不需要打序列化标签,
/// <summary>
/// 保存地图数据
/// </summary>
public static void SaveMap()
{
if (!Directory.Exists(Application.dataPath + "/MapData/"))
{
Directory.CreateDirectory((Application.dataPath + "/MapData/"));
}
BinaryFormatter formatter = new BinaryFormatter();//二进制转化
FileStream file2 = File.Create(Application.dataPath + "/MapData/MapDataJSON.txt");// 1 创建存储文件
var json2 = JsonUtility.ToJson(MapAllData.transscriptData);// 2 能覆写回来
formatter.Serialize(file2, json2);//(1,2)
file2.Dispose();
file2.Close();
}
注意如果正保存状态的话, 不要关闭.
public static TileMapSerializeData ReadMap()
{
Debug.Log("从这里读取");
MapAllData.MapData = new TileMapSerializeData() ;
BinaryFormatter bf2 = new BinaryFormatter();
if (File.Exists(Application.dataPath + "/MapData/MapDataJSON.txt"))
{
FileStream file2 = File.Open(Application.dataPath + "/MapData/MapDataJSON.txt", FileMode.Open);//打开文件
JsonUtility.FromJsonOverwrite((string)bf2.Deserialize(file2), MapAllData.MapData);//反序列化
file2.Close();
}
else
{
return MapData;
// text.text = "读取失败";
}
if (MapAllData.MapData == null)
{
return MapData;
// text.text = "读取失败";
}
else
{
// text.text = "读取完成";
Debug.Log("读取完成");
return MapData;
}
}