Serialize&Deserialize
目录
1.XML
1.1 XML序列化/反序列化
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
namespace XMLSerialize
{
public class UserInfo
{
public int Id;
public string UserName;
public string UserPass;
public string Email;
public DateTime RegTime;
}
class Program
{
private static List<UserInfo> list = new List<UserInfo>()
{
new UserInfo()
{Id = 1,UserName = "Kyle",UserPass = "FDASDFAS",Email = "zhangsan@163.com",RegTime = DateTime.Now},
new UserInfo()
{Id = 2,UserName = "Bob",UserPass = "FDASDFAS",Email = "lisi@163.com",RegTime = DateTime.Now},
new UserInfo()
{Id = 3,UserName = "Lily",UserPass = "FDASDFAS",Email = "wangwu@163.com",RegTime = DateTime.Now},
new UserInfo()
{Id = 4,UserName = "John",UserPass = "FDASDFAS",Email = "zhaoliu@163.com",RegTime = DateTime.Now},
new UserInfo()
{Id = 5,UserName = "David",UserPass = "FDASDFAS",Email = "tianqi@163.com",RegTime = DateTime.Now},
new UserInfo()
{Id = 6,UserName = "Nancy",UserPass = "FDASDFAS",Email = "wangba@163.com",RegTime = DateTime.Now}
};
static void Main(string[] args)
{
//序列化对象生成文件
WriteSingleXml();
//反序列化文件生成对象
ReadListXml();
Console.ReadKey();
}
private static void WriteSingleXml()
{
//序列化集合为xml文件
Console.WriteLine("collection to xml");
var reader = new XmlSerializer(typeof(List<UserInfo>));
//写入文件
using (var fs = File.OpenWrite(@"D:\UserInfo.xml"))
{
reader.Serialize(fs, list);
}
Console.WriteLine("write in succeed");
}
private static void ReadListXml()
{
//反序列化文件
Console.WriteLine("xml to collection");
var reader = new XmlSerializer(typeof(List<UserInfo>));
using (var fs = File.OpenRead(@"D:\UserInfo.xml"))
{
var result = reader.Deserialize(fs) as List<UserInfo>;
foreach (var r in result)
{
Console.WriteLine(r.Email);
}
//result.ForEach(Console.WriteLine);
}
Console.WriteLine("deserialize succeed");
}
}
}
output
collection to xml
write in succeed
xml to collection
zhangsan@163.com
lisi@163.com
wangwu@163.com
zhaoliu@163.com
tianqi@163.com
wangba@163.com
deserialize succeed
XML
<?xml version="1.0"?>
<ArrayOfUserInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<UserInfo>
<Id>1</Id>
<UserName>Kyle</UserName>
<UserPass>FDASDFAS</UserPass>
<Email>zhangsan@163.com</Email>
<RegTime>2018-09-19T14:51:03.3560463+08:00</RegTime>
</UserInfo>
<UserInfo>
<Id>2</Id>
<UserName>Bob</UserName>
<UserPass>FDASDFAS</UserPass>
<Email>lisi@163.com</Email>
<RegTime>2018-09-19T14:51:03.3560463+08:00</RegTime>
</UserInfo>
...
</ArrayOfUserInfo>
1.2 创建XML文件
2.Json
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace JsonSerializerAndDeSerializer
{
[DataContract] // 使用DataContractJsonSerializer必需
public class Student
{
[DataMember]
public int ID { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
[DataMember]
public string Sex { get; set; }
}
}
2.1 DataContractJsonSerializer
using System.Runtime.Serialization.Json;
Student stu = new Student()
{
ID = 1,
Name = "kyle",
Sex = "male",
Age = 23
};
//序列化
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Student));
MemoryStream msObj = new MemoryStream();
//将序列化之后的Json格式数据写入流中
js.WriteObject(msObj, stu);
msObj.Position = 0;
//从0这个位置开始读取流中的数据
StreamReader sr = new StreamReader(msObj, Encoding.UTF8);
string json = sr.ReadToEnd();
sr.Close();
msObj.Close();
Console.WriteLine(json);
//反序列化
string toDes = json;
//string to = "{\"ID\":\"1\",\"Name\":\"kyle\",\"Sex\":\"male\",\"Age\":\"1230\"}";
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(toDes)))
{
DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(typeof(Student));
Student model = (Student)deseralizer.ReadObject(ms);// //反序列化ReadObject
Console.WriteLine("ID=" + model.ID);
Console.WriteLine("Name=" + model.Name);
Console.WriteLine("Age=" + model.Age);
Console.WriteLine("Sex=" + model.Sex);
}
Console.ReadKey();
2.2 JavaScriptSerializer
using System.Web.Script.Serialization;
Student stu = new Student()
{
ID = 1,
Name = "Bob",
Age = 18,
Sex = "male"
};
JavaScriptSerializer js = new JavaScriptSerializer();
string jsonData = js.Serialize(stu);//序列化
Console.WriteLine(jsonData);
////反序列化方式一:
string desJson = jsonData;
Student model = js.Deserialize<Student>(desJson);// 反序列化
string message = string.Format("ID={0},Name={1},Age={2},Sex={3}", model.ID, model.Name, model.Age, model.Sex);
Console.WriteLine(message);
Console.ReadKey();
////反序列化方式2
dynamic modelDy = js.Deserialize<dynamic>(desJson); //反序列化
string messageDy = string.Format("动态的反序列化,ID={0},Name={1},Age={2},Sex={3}",
modelDy["ID"], modelDy["Name"], modelDy["Age"], modelDy["Sex"]);//这里要使用索引取值,不能使用对象.属性
Console.WriteLine(messageDy);
Console.ReadKey();
2.3 JSON.NET包
首先安装newtonsoft.JSON或在Visual Studio中,工具菜单->管理NuGet包->搜索JSON.NET包
using Newtonsoft.Json;
List<Student> lstStuModel = new List<Student>()
{
new Student(){ID=1,Name="A",Age=250,Sex="male"},
new Student(){ID=2,Name="B",Age=300,Sex="female"}
};
//Json.NET序列化
string jsonData = JsonConvert.SerializeObject(lstStuModel);
Console.WriteLine(jsonData);
Console.ReadKey();
//Json.NET反序列化
string json = @"{ 'Name':'C#','Age':'3000','ID':'1','Sex':'女'}";
Student descJsonStu = JsonConvert.DeserializeObject<Student>(json);//反序列化
Console.WriteLine(string.Format("反序列化: ID={0},Name={1},Sex={2},Sex={3}", descJsonStu.ID, descJsonStu.Name, descJsonStu.Age, descJsonStu.Sex));
Console.ReadKey();
把圈子变小,把语言变干净,把成绩往上提,把故事往心里收,现在想要的以后你都会有。