62,267
社区成员
发帖
与我相关
我的任务
分享static void Main(string[] args)
{
Person[] People = {
new Person(1, "A"),
new Person(2, "B"),
new Person(3, "C"),
new Person(4, "D"),
new Person(5, "E")
};
System.Runtime.Serialization.Json.DataContractJsonSerializer jsonFormator = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(Person[]));
byte[] buff = new byte[1024];
System.IO.Stream stream = new System.IO.MemoryStream(buff);
jsonFormator.WriteObject(stream, People); // 序列化
string str = System.Text.Encoding.UTF8.GetString(buff).TrimEnd('\0');
Console.WriteLine(str);
// 反序列化
System.IO.Stream rS = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(str));
Person[] persons = jsonFormator.ReadObject(rS) as Person[];
Console.WriteLine(persons[2].Name);
}
[System.Runtime.Serialization.DataContract] //必须加这个属性
class Person
{
[System.Runtime.Serialization.DataMember] // 该属性注明要序列化的成员
public int Id { get; set; }
[System.Runtime.Serialization.DataMember]
public string Name { get; set; }
public Person(int id, string name)
{
Id = id;
Name = name;
}
}