C# Jason 序列化到文件 和从文件反序列化到对象

本文介绍了一个简单的C#程序实例,展示了如何使用Newtonsoft.Json库进行对象的JSON序列化与反序列化操作,并将序列化后的JSON数据写入文件,再从文件中读取并转换为对象。

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

应用:https://www.cnblogs.com/caofangsheng/p/5687994.html

以下是全部代码:

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

using Newtonsoft.Json;
using System.IO;


namespace JasonTest
    {
    public class Student
        {
        public int ID { get; set; }


        public string Name { get; set; }


        public int Age { get; set; }


        public string Sex { get; set; }
        }


    class Program
        {


        static void Serial()
            {
            //序列化对象
            Student one = new Student()
                { ID = 1, Name = "武松", Age = 250, Sex = "男" };


            //序列化
            string jsonData = JsonConvert.SerializeObject(one);      


             FileStream nFile = new FileStream("jsonTest.txt", FileMode.CreateNew);
             StreamWriter writer = new StreamWriter(nFile);
             writer.Write(jsonData);
             writer.Close();    //写到文件


            Console.WriteLine(jsonData);  //显示结果
            Console.ReadLine();
            }


        static void DiserialData()
            {
            FileStream file = new FileStream("jsonTest.txt", FileMode.Open);
            StreamReader sr = new StreamReader(file);


            string readJson = sr.ReadToEnd();   //从文件读出来


            Student descJsonStu = JsonConvert.DeserializeObject<Student>(readJson);//反序列化


            Console.WriteLine(descJsonStu.ID);
            Console.WriteLine(descJsonStu.Name);
            Console.WriteLine(descJsonStu.Age);
            Console.WriteLine(descJsonStu.Sex);


            Console.ReadLine();


            }
        static void Main(string[] args)
            {
            // Serial();   //序列化到文件


            DiserialData();//从文件 反序列化到对象
            }
        }

    }

运行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值