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