class Program
{
static void Main(string[] args)
{
Serialize();
Deserialize();
Console.ReadLine();
}
static void Deserialize()
{
String str = "{\"Age\":20,\"Name\":\"张三\"}";
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(Student));
using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(str)))
{
Student stu = (Student)json.ReadObject(stream);
Console.WriteLine(stu.Name+":"+stu.Age);
}
}
static void Serialize()
{
Student stu = new Student("张三", 20);
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(Student));
using (MemoryStream stream = new MemoryStream())
{
json.WriteObject(stream, stu);
String str = System.Text.Encoding.UTF8.GetString(stream.ToArray());
Console.WriteLine(str);
}
}
}
[System.Runtime.Serialization.DataContract(Namespace = "http://www.mzwu.com/")]
class Student
{
[System.Runtime.Serialization.DataMember]
public String Name { get; set; }
[System.Runtime.Serialization.DataMember]
public int Age { get; set; }
public Student(String name, int age)
{
this.Name = name;
this.Age = age;
}
}