zoukankan      html  css  js  c++  java
  • C#使用DataContractJsonSerializer实现Json格式的序列化和反序列化

    实体类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!

  • 相关阅读:
    D2. Remove the Substring (hard version)(思维 )
    暑假集训
    AcWing:167. 木棒(dfs + 剪枝)
    AcWing:109. 天才ACM(倍增 + 归并排序)
    AcWing:99. 激光炸弹(前缀和)
    B. Interesting Array(线段树)
    Best Reward HDU
    G. Swapping Places
    How many HDU
    GSS4&&花仔游历各国
  • 原文地址:https://www.cnblogs.com/ldqwyl/p/2015733.html
Copyright © 2011-2022 走看看