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

 

相关文章

AJAX是一种基于JavaScript和XML的技术,能够使网页实现异步交...
在网页开发中,我们常常需要通过Ajax从后端获取数据并在页面...
在前端开发中,经常需要循环JSON对象数组进行数据操作。使用...
AJAX(Asynchronous JavaScript and XML)是一种用于创建 We...
AJAX技术被广泛应用于现代Web开发,它可以在无需重新加载页面...
Ajax是一种通过JavaScript和HTTP请求交互的技术,可以实现无...