您的位置:首页 > Web前端 > JavaScript

Json序列化和反序列化--Newtonsoft.Json

2022-04-11 00:10 639 查看 https://www.cnblogs.com/zhangd

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

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: