实体类Student:
程序代码
/// <summary>
/// 学生实体类
/// </summary>
[System.Runtime.Serialization.DataContract(Namespace="http://www.mzwu.com/")]
public class Student
{
private string _Name;
private int _Age;
public Student(string name, int age)
{
_Name = name;
_Age = age;
}
/// <summary>
/// 姓名
/// </summary>
[System.Runtime.Serialization.DataMember]
public string Name
{
set {_Name = value;}
get { return _Name; }
}
/// <summary>
/// 年龄
/// </summary>
[System.Runtime.Serialization.DataMember]
public int Age
{
set { _Age = value; }
get { return _Age; }
}
}
注意:必须使用DataContractAttribute对类进行标记,使用DataMemberAttribute类成员进行标记,否则该类无法被序列化。
对象转为JSON字符串
程序代码
Student stu = new Student("小李", 30);
System.Runtime.Serialization.Json.DataContractJsonSerializer json = new System.Runtime.Serialization.Json.DataContractJsonSerializer(stu.GetType());
using (MemoryStream stream = new MemoryStream())
{
json.WriteObject(stream, stu);
Response.Write(System.Text.Encoding.UTF8.GetString(stream.ToArray()));
}
JSON字符串转为对象
程序代码
System.Runtime.Serialization.Json.DataContractJsonSerializer json = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(Student));
using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes("{\"Age\":20,\"Name\":\"张三\"} ")))
{
Student stu = (Student)json.ReadObject(stream);
Response.Write(string.Format("name:{0},age:{1}", stu.Name, stu.Age));
}
注:.NET Framework 3.5下才可用DataContractJsonSerializer!