C# Bin、XML、Json的序列化和反序列化
1)序列化前的准备 |
声明类:
[Serializable]
public class BandItem
{
//JsonIgnore:当不想把某字段值序列化到Json时使用
//[JsonIgnore]
public string Name { get; set; }
public string MusicStyle { get; set; }
public string Masterpiece { get; set; }
public BandItem(string name, string musicStyle, string masterpiece)
{
Name = name;
MusicStyle = musicStyle;
Masterpiece = masterpiece;
}
}
初始化集合:
public List<BandItem> InitList()
{
List<BandItem> bandList = new List<BandItem>()
{
new BandItem("房东的猫","民谣","下一站茶山刘"),
new BandItem("Beyond","摇滚","海阔天空")
};
return bandList;
}
2)bin 文件的序列化和反序列化 |
写文件(序列化):
public void BinSerialize(List<BandItem> list)
{
Stream stream = new FileStream("test.bin", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(stream, list);
stream.Close();
}
读文件(反序列化):
public List<BandItem> BinDeserialize(string filePath)
{
Stream stream = new FileStream(filePath, FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
List<BandItem> list = (List<BandItem>)bf.Deserialize(stream);
stream.Close();
return list;
}
3)XML 的序列化和反序列化 |
序列化为 XML:
public string XMLSerialize(List<BandItem> list)
{
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(list.GetType());
StringWriter sw = new StringWriter();
x.Serialize(sw, list);
string xml = sw.ToString();
return xml;
}
XML反序列化:
public List<BandItem> XMLDeserialize(string xml)
{
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(List<BandItem>));
StringReader sr = new StringReader(xml);
var list = (List<BandItem>)x.Deserialize(sr);
return list;
}
4)Json 的序列化和反序列化 |
需要一个程序包,在程序包管理控制台里输入安装命令:Install-Package Newtonsoft.Json
序列化为Json:
public string JsonSerialize(List<BandItem> list)
{
string json = JsonConvert.SerializeObject(list);
return json;
}
Json反序列化:
public List<BandItem> JsonDeserialize(string json)
{
List<BandItem> list = JsonConvert.DeserializeObject<List<BandItem>>(json);
return list;
}
5)序列化转换的模板 |
统一集合里的类型,编写成一个模板:
//对序列化和反序列化的处理
public static class SerializeConver
{
//Bin文件的序列化
public static bool BinSerializable<T>(T list,string newFilePath)
{
try
{
Stream stream = new FileStream(newFilePath, FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(stream, list);
stream.Close();
return true;
}
catch(Exception ex)
{
return false;
}
}
//Bin文件的反序列化
public static T BinDeserialize<T>(string sourceFilePath)
{
Stream stream = new FileStream(sourceFilePath, FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
T list = (T)bf.Deserialize(stream);
stream.Close();
return list;
}
//可扩展其他格式的序列化和反序列模板...
}
模板的使用:
var list = InitList();
var isSerial = SerializeConver.BinSerializable<List<BandItem>>(list,"test.bin");
var readList = SerializeConver.BinDeserialize<List<BandItem>>("test.bin");