您的位置:首页 > Web前端 > JavaScript

some thing about JSon

2009-12-31 10:41 337 查看
实体类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("张三", 20);
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));
}



文章转载自:http://www.mzwu.com/article.asp?id=1913

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: