c# 读取json 写json 序列化与反序列化 .net 4.0

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;
        }
    }

posted on 2012-07-15 20:23  雨渐渐  阅读(1131)  评论(0编辑  收藏  举报

导航