Json序列化和反序列化--Newtonsoft.Json
using Newtonsoft.Json;
写入文件,读取文件后,要及时释放FileStream ,StreamWriter StreamReader ,否则可能导致读写失败;
反序列化使用泛型方法,而不应使用as转换;
as可能导致转型失败;
JsonConvert.DeserializeObject<CStudent>(json)
string path = Application.StartupPath + @"\data.json"; private void button2_Click(object sender, EventArgs e) { listBox1.Items.Add(path); CStudent student = new CStudent() { Name = "Tome", Sex = "male", Age = 18 }; string json = JsonConvert.SerializeObject(student); using (FileStream stream = new FileStream(path, FileMode.OpenOrCreate)) { StreamWriter sw = new StreamWriter(stream); sw.Write(json); sw.Dispose(); } }
private void button3_Click(object sender, EventArgs e) { listBox1.Items.Clear(); if (!File.Exists(path)) return; string json =null; using (FileStream stream = new FileStream(path, FileMode.Open)) { StreamReader sr = new StreamReader(stream); json = sr.ReadToEnd(); sr.Dispose(); } listBox1.Items.Add("(json ==null)?" + (json == null)); if (json ==null) return; var student3 = JsonConvert.DeserializeObject<CStudent>(json); listBox1.Items.Add(student3.Name); listBox1.Items.Add(student3.Sex); listBox1.Items.Add(student3.Age); listBox1.Items.Add("Say():"+student3.Say()); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)