Newtonsoft.Json use

此博客展示了一段C#代码,主要实现了学生数据的JSON序列化与反序列化。代码创建了学生列表,将其转换为JSON字符串输出,还构建了字典数据并转换为JSON,最后对JSON数据进行反序列化操作,运行环境为Windows。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


        private void button3_Click(object sender, EventArgs e)
        {
            List<Student> students = new List<Student>();

            students.Add(new Student { Id = 1, Name = "张三", Sex = "男", Description = "班长" });

            students.Add(new Student { Id = 2, Name = "李四", Sex = "女", Description = "小组长" });

            students.Add(new Student { Id = 3, Name = "王五", Sex = "男", Description = "宣传委员" });


            string studentsJson = JsonConvert.SerializeObject(students);
            MessageBox.Show(studentsJson);
            Console.WriteLine(studentsJson);


            //
            Dictionary<String, Object> dicList = new Dictionary<string, object>();
            Dictionary<String, string> dicSampleList = new Dictionary<string, string>();
            dicSampleList.Add("key_1", "111");
            dicSampleList.Add("key_2", "222");
            dicList.Add("SampleDatas", dicSampleList);
            List<Dictionary<string, object>> tableItems = new List<Dictionary<string, object>>();
            var properties = typeof(Student).GetProperties();

            foreach (var stu in students)
            {
                Dictionary<string, object> row = new Dictionary<string, object>();
                foreach (System.Reflection.PropertyInfo info in properties)
                {
                    var value = stu.GetType().GetProperty(info.Name).GetValue(stu, null);
                    //Console.WriteLine(info.Name,value);
                    row.Add(info.Name,value);
                    
                }
                tableItems.Add(row);
            }
            
            dicList.Add("Table1", tableItems);
            string customJson = JsonConvert.SerializeObject(dicList);
            MessageBox.Show(customJson);
            Console.WriteLine(customJson);

            var desobj = JsonConvert.DeserializeObject<Dictionary<string, object>>(customJson);
            var dicSample =JsonConvert.DeserializeObject<Dictionary<string, object>>(desobj["SampleDatas"].ToString());
            var dicTable1 = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(desobj["Table1"].ToString());

            Console.WriteLine(desobj.ToString());
            MessageBox.Show(desobj.ToString());
        }
      

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值