JSON 通过强类型或者匿名对象 序列化和反序列化 对象和集合

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JSONSerializeDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // 簡單的將 對象 序列化成 字符串
            Student s = new Student("張三", "男人", 9);
            //Student s = new Student();
            //s.name = "張三";
            //s.sex = "男人";
            //s.age = 29;
            string sj = JsonConvert.SerializeObject(s); // "{\"name\":\"張三\",\"sex\":\"男人\",\"age\":9}"

            // 將JSON字符串反序列化成对象
            // 1.指定反序列化的对象
            //object o = JsonConvert.DeserializeObject(sj, typeof(Student));
            //Student s2 = o as Student; // "張三", "男人", 9

            //2.反序列化使用匿名对象
            //var Stutemp = new {
            //    name = "",
            //    sex = "",
            //    age = 0
            //};
            //var s2 = JsonConvert.DeserializeAnonymousType(sj, Stutemp);

            //3.序列化 对象集合
            List<Student> list = new List<Student>
            {
               new Student("張三", "男人", 9),
               new Student("李四", "男人", 25),
               new Student("小李", "女人", 35)
             };

            string slist = JsonConvert.SerializeObject(list);//"[{\"name\":\"張三\",\"sex\":\"男人\",\"age\":9},{\"name\":\"李四\",\"sex\":\"男人\",\"age\":25},{\"name\":\"小李\",\"sex\":\"女人\",\"age\":35}]"
            //4,指定对象反序列化集合
            //List<Student> slist2=JsonConvert.DeserializeObject<List<Student>>(slist);

            //5.指定匿名对象反序列化集合
            var Stutemp = new
            {
                name = "",
                sex = "",
                age = 0
            };
            var listtemp = Enumerable.Repeat(Stutemp, 3);// 生成匿名集合对象
            var listo=JsonConvert.DeserializeAnonymousType(slist, listtemp);

            foreach(var s2 in listo)
            {
                Console.WriteLine(s2.name + "  " + s2.sex + "  " + s2.age);
            }


            //Console.WriteLine(s2.name +"  "+s2.sex+"  "+s2.age);
            Console.ReadKey();
        }
    }
    public class Student
    {
        public Student() { }
        public Student(string _name,string _sex,int _age)
        {
            name = _name;
            sex = _sex;
            age = _age;
        }
        public string name;
        public string sex;
        public int age;

        public override string ToString()
        {
            return name + "   " + sex + "    " + age;
        }
    }
}

  

posted @ 2021-08-09 20:25  zq爱生活爱代码  阅读(153)  评论(0编辑  收藏  举报