实现json的序列化和反序列化
//实现json的序列化和反序列化
Person Person = new Person();
Person.Id = 1;
Person.Name = "小白";
DataContractJsonSerializer json = new DataContractJsonSerializer(Person.GetType());
string szJson = "";
//序列化
using (MemoryStream stream = new MemoryStream())
{
json.WriteObject(stream, Person);
szJson = Encoding.UTF8.GetString(stream.ToArray());
}
//反序列化
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Person));
Person _people = (Person)serializer.ReadObject(ms);
}
namespace ReadJson
{
[DataContract]
public class Person
{
[DataMember(Name = "id")]
public int Id { get; set; }
[DataMember(Name = "Name")]
public string Name { get; set; }
}
}